以编程方式指定动态数组索引

时间:2011-04-03 14:49:55

标签: r

我想概括这段代码来处理任意数量维的数组,但我不确定如何以编程方式指定数组索引。我认为它可以通过粘贴评估替代引用的一些组合,但我无法弄明白。

x <- array(runif(1000),dim=c(10,10,10))
w <- vector("list")

for (i in seq(dim(x)[1]))
{
    w[i] <- list(which(x[i,,] == max(x[i,,]),arr.ind=TRUE))
}

for (i in seq(dim(x)[1]))
{
    # looking for something like:
    # s <- paste(i,",",paste(w[[i]],collapse=","),sep="")
    # v <- x[s]
    v <- x[i,w[[i]][[1]],w[[i]][[2]]]
    print(paste("the max at index",i,"is",round(v,4)),quote=FALSE)
}

1 个答案:

答案 0 :(得分:0)

nvm,想出怎么做

x <- array(runif(1000),dim=c(10,10,10))
w <- vector("list")

for (i in seq(dim(x)[1]))
{
    w[i] <- list(which(x[i,,] == max(x[i,,]),arr.ind=TRUE))
}

for (i in seq(dim(x)[1]))
{
    v <- do.call(`[`,c(list(x,i),w[[i]]))
    print(paste("the max at index",i,"is",round(v,4)),quote=FALSE)
}