specify dynamic array indexes programmatically
I'd like to generalize this code to handle an array of any number of dimensions but I'm not sure how to specify array indexes programatically. I think its 开发者_运维百科possible with some combination of paste eval substitute quote but I can't figure it out.
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)
}
nvm, figured out how to do it
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)
}
精彩评论