我查看了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]]
}
有关如何以更快的方式做到这一点的任何想法?
也许你可以使用'purrr:地图()'? – Jeremy
我不熟悉'purrr'软件包,所以我不得不查看它并回复你。 –