我查看了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'軟件包,所以我不得不查看它並回復你。 –