编辑:有人说问题不清楚,已编辑。
我制作了一个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]))
}
}
最佳答案
根据澄清,也许这可行 - 从 E[, , 1]
获取“g”、“t”、“d”的行/列索引,循环遍历 nPeriods
从 2 开始,并通过使用 gidx
使用 cbind
创建的 matrix
索引对元素进行子集化来更新“结果” 、 tidx
和 didx
与 i
或 i-1
递归更新
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
关于在 R 中的 For 循环中引用数组中的元素 - 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71372068/