我已经查看了 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 x 3900 x 35 x 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]]
}
关于如何以更快的方式做到这一点有什么想法吗?
最佳答案
据我从你的问题中可以看出,你只是在寻找矩阵索引。
考虑以下简化示例。
首先,您的数组
(具有 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
关于r - 使用数据帧中的值作为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46671503/