使用数据框中的值作为数组索引
我查看了StackOverflow上的以前的问题,但还没有找到适用于我遇到的问题的解决方案。使用数据框中的值作为数组索引
基本上,我有一个数据帧,我们会打电话给df
,看起来像这样:
source destination year ship count
1 1415 1 6 0
1 1415 2 6 0
1 1415 3 6 0
1 1415 4 6 0
1 1415 5 6 0
1 1415 6 6 0
可复制的代码,你应该在这里需要它:
df <- structure(list(source = c(1L, 1L, 1L, 1L, 1L, 1L), destination =
c(1415, 1415, 1415, 1415, 1415, 1415), year = 1:6, ship = c(6,
6, 6, 6, 6, 6), count = c(0, 0, 0, 0, 0, 0)), .Names = c("source",
"destination", "year", "ship", "count"), class = "data.frame",
row.names = c(NA, 6L))
我也有一个四维阵列我们会打电话给m1
。实质上,df
的前四列中的每一列对应于m1
的四个维度中的每一个 - 基本上是索引。正如您现在可能猜到的那样,df
的第五列对应于实际存储在m1
中的值。
因此,例如,df$count[3] <- m1[1,1415,3,6]
。
目前,整个count
列是空的,我想填写它。如果这是一个小任务,我会用慢而笨的方法来做,并使用for循环,但是问题是df
有大约300,000,000行,并且m1
的尺寸大约是3900×3900×35×7。因此,以下方法在运行一整天后只能通过5%的行:
for(line in 1:nrow(df)){
print(line/nrow(backcastdf))
df$count[line] <- m1[df$source[line], df$destination[line], df$year[line], df$ship[line]]
}
有关如何以更快的方式做到这一点的任何想法?
据我所知你的问题,你只是寻找矩阵索引。
请考虑以下简化示例。
首先,你的array
(有4个维度)。
dim1 <- 2; dim2 <- 4; dim3 <- 2; dim4 <- 2
x <- dim1 * dim2 * dim3 * dim4
set.seed(1)
M <- `dim<-`(sample(x), list(dim1, dim2, dim3, dim4))
M
## , , 1, 1
##
## [,1] [,2] [,3] [,4]
## [1,] 9 18 6 29
## [2,] 12 27 25 17
##
## , , 2, 1
##
## [,1] [,2] [,3] [,4]
## [1,] 16 5 14 20
## [2,] 2 4 8 32
##
## , , 1, 2
##
## [,1] [,2] [,3] [,4]
## [1,] 31 28 24 7
## [2,] 15 11 3 23
##
## , , 2, 2
##
## [,1] [,2] [,3] [,4]
## [1,] 13 1 21 30
## [2,] 19 26 22 10
##
其次,您的data.frame
具有感兴趣的指标。
mydf <- data.frame(source = c(1, 1, 2, 2),
destination = c(1, 1, 2, 3),
year = c(1, 2, 1, 2),
ship = c(1, 1, 2, 1),
count = 0)
mydf
## source destination year ship count
## 1 1 1 1 1 0
## 2 1 1 2 1 0
## 3 2 2 1 2 0
## 4 2 3 2 1 0
三,提取物:
out <- M[as.matrix(mydf[1:4])]
out
# [1] 9 16 11 8
四,比较:
M[1, 1, 1, 1]
# [1] 9
M[1, 1, 2, 1]
# [1] 16
M[2, 2, 1, 2]
# [1] 11
M[2, 3, 2, 1]
# [1] 8
哦,男人,真的那么简单吗?等等,让我检查一下我的数据,然后我会回复你。 –
刚刚检查 - 完美的作品,只花了大约一分钟。 –
也许你可以使用'purrr:地图()'? – Jeremy
我不熟悉'purrr'软件包,所以我不得不查看它并回复你。 –