編輯:有人說問題不清楚,已編輯。
我制作了一個 3 維陣列,并分配了如下值:
D <- c('g', 't', NA, 'd')
nPeriods = 4
column.names = c('aaa', 'bbb')
row.names = c('jjj', 'hhh')
threeD.names = c(1:nPeriods)
E = array(c(D), dim=c(2, 2, nPeriods),
dimnames = list(row.names, column.names, threeD.names))
values <- c(g = 5,
t = 2,
d = 7)
G <- apply(E, 1:3, function(x) values[x])
現在我想創建一個 for 回圈,執行以下操作:
for (i in 2:nPeriods){
G[1,1,i]=G[1,1,i-1]*G[2,1,i-1] G[2,2,i]
}
但是我不想每次想寫這樣的東西時都必須找到g,t和d的位置。如果可能的話,我只想能夠使用 g、t 和 d。
問題到此結束。
下面是一些有用的代碼,可能適用于找到解決方案?
我有這段代碼查找并回傳每個值的索引:
result <- G
for (i in 2:dim(G)[3]) {
idx <- which(E[, , 1] == 'g', arr.ind = T)
row <- idx[1, 'row']
col <- idx[1, 'col']
result[row, col, i] <- result[row, col, i-1] * 2
}
對于一個更簡單的問題,但我的真實陣列很大,所以為每個元素撰寫會很長。有沒有辦法自動化這個?
他們還提出了這一點 - 這對于簡單的總和非常有用,但我不確定它如何適用于我上面的總和型別:
funcs <- c(g = '*', t = ' ', d = '-')
modifiers <- c(g = 2, t = 3, d = 4)
G <- apply(E, 1:3, function(x) values[x])
result <- G
for (i in 2:dim(G)[3]) {
for (j in names(values)) {
idx <- which(E[, , 1] == j, arr.ind = T)
row <- idx[1, 'row']
col <- idx[1, 'col']
result[row, col, i] <- do.call(funcs[j], args = list(result[row, col, i-1], modifiers[j]))
}
}
uj5u.com熱心網友回復:
根據澄清,也許這可行 - 從 中獲取“g”、“t”、“d”的行/列索引,從 2E[, , 1]回圈,并通過使用創建的索引nPeriods對元素進行子集化來更新“結果” matrixwith cbindusing gidx, tidxand didxwith ior i-1to 遞回更新
result <- G
gidx <- which(E[, , 1] == 'g', arr.ind = TRUE)
tidx <- which(E[, , 1] == 't', arr.ind = TRUE)
didx <- which(E[, , 1] == 'd', arr.ind = TRUE)
for (i in 2:nPeriods) {
result[cbind(gidx, i)] <- result[cbind(gidx, i-1)] *
result[cbind(tidx, i-1)] result[cbind(didx, i)]
}
-輸出
> result
, , 1
aaa bbb
jjj 5 NA
hhh 2 7
, , 2
aaa bbb
jjj 17 NA
hhh 2 7
, , 3
aaa bbb
jjj 41 NA
hhh 2 7
, , 4
aaa bbb
jjj 89 NA
hhh 2 7
-檢查OP的輸出
resultold <- G
for (i in 2:nPeriods){
resultold[1, 1, i] <- resultold[1,1,i-1]* resultold[2,1,i-1] resultold[2,2,i]
}
identical(result, resultold)
[1] TRUE
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438416.html
下一篇:用數字替換陣列中的字符
