6

我在看 3 维数组 M:M<-dim(3,3,3)

我想找到一种使用以下规则填充 M 的有效方法: M[i,j,k] = i/10 + j^2 + sqrt(k),理想情况下无需编写带有for语句的循环。

为澄清起见,如果 M 是二维的,则有一种简单的方法可以完成此操作。如果我想要 M[i,j] = i/10 + j^2,那么我可以这样做 M<-row(M)/10 + col(M)*col(M)

3维或更高维数组是否有等效的东西?

4

4 回答 4

7

@James 的答案更好,但我认为你的问题的狭义答案(多维等价于row()/col())是slice.index......

M<- array(dim=c(3,3,3))
slice.index(M,1)/10+slice.index(M,2)^2+sqrt(slice.index(M,3))

r-devel如果有人(我或其他人)在列表上发布建议以slice.index?row/ ?col...

或者(类似于@flodel 的新答案):

d <- do.call(expand.grid,lapply(dim(M),seq)) ## create data.frame of indices
v <- with(d,Var1/10+Var2^2+sqrt(Var3))       ## default names Var1, ... Varn 
dim(v) <- dim(M)                             ## reshape into array
于 2012-10-24T18:10:53.910 回答
4

使用嵌套outer的 s 怎么样?

outer(1:3/10,outer((1:3)^2,sqrt(1:3),"+"),"+")
, , 1

     [,1] [,2] [,3]
[1,]  2.1  5.1 10.1
[2,]  2.2  5.2 10.2
[3,]  2.3  5.3 10.3

, , 2

         [,1]     [,2]     [,3]
[1,] 2.514214 5.514214 10.51421
[2,] 2.614214 5.614214 10.61421
[3,] 2.714214 5.714214 10.71421

, , 3

         [,1]     [,2]     [,3]
[1,] 2.832051 5.832051 10.83205
[2,] 2.932051 5.932051 10.93205
[3,] 3.032051 6.032051 11.03205
于 2012-10-24T18:07:44.127 回答
2

您还可以使用arrayInd

M   <- array(dim = c(3, 3, 3))
foo <- function(dim1, dim2, dim3) dim1/10 + dim2^2 + sqrt(dim3)
idx <- arrayInd(seq_along(M), dim(M), useNames = TRUE)
M[] <- do.call(foo, as.data.frame(idx))

我觉得随着维度数量的增加,这种方法有可能减少打字。

于 2012-10-24T19:50:39.047 回答
1

可以说是从“零基础”做起。

 i <- rep(1:3, times=3*3)
 j <- rep(1:3 , times= 3, each=3)
 k <- rep(1:3 , each= 3*3)
 M <- array( i/10 + j^2 + sqrt(k), c(3, 3, 3))
 M
于 2012-10-24T19:45:31.107 回答