在R中重新整形数组的同时填充给定的维度

时间:2013-07-01 19:40:08

标签: r

假设我对n网格上的某些字段进行了100x100次观察,并且此数据存储为单个向量obs。我想将其重塑为100x100xn数组而不知道n是什么进展。在matlab中我可以使用

reshape(obs,100,100,[]);

或在python中

np.reshape(obs,(100,100,-1))

R中是否有类似的功能,还是我必须手动计算最后一个索引的大小?

3 个答案:

答案 0 :(得分:2)

这是你想要的吗?

 dim(obs) <- c(100,100,length(v)/100/100)

例如:

v <- seq(2*2*3)
dim(v) <- c(2,2,length(v)/2/2)

, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12

请注意

  v <- seq(2*2*3+1)

您将收到错误消息:

Error in dim(v) <- c(2, 2, length(v)/2/2) : 
  dims [product 12] do not match the length of object [13]

答案 1 :(得分:2)

试试这个(我相信你可以根据你的需要调整它):

shaper <- function(obs, a, b) {
 array(obs, dim=c(a, b, length(obs)/a/b))
}
shaper(obs, 100, 100)

如果您不确定尺寸是否正确,您可以查看是否有残留物,如下所示:

shaper <- function(obs, a, b) {
  dimension <- length(obs)/a/b 
  if (dimension %% 1 != 0) { 
   stop("not correctly divisible")
  }
  else {
   return(array(obs, dim=c(a, b, dimension)))
  }
}
shaper(obs, 100, 100)

还添加了将任意数量的维度作为输入的功能,并尝试将其扩展为1.

shaper <- function(obs, ...) {
 len.remaining <- length(obs)
 for (i in c(...)) {
   len.remaining <- len.remaining / i
 }
 if (len.remaining %% 1 != 0) { 
  stop("not correctly divisible")
 }
 else {
  return(array(obs, dim=c(..., len.remaining)))
 } 
}

现在可以使用:

obs <- rep(1, 100 * 100 * 5)
> res <- shaper(obs, 100, 100)
> dim(res) 
[1] 100 100 5
> res <- shaper(obs, 10, 10, 100)
> dim(res)
[1] 10 10 100 5

答案 2 :(得分:0)

使用上面的dualinity代码我实现了一个类似于np.reshape语法的R函数

npreshape <- function(x,shape) {
    x<- array(x)
    ind <- which(shape ==  -1)
    shape[ind] = prod(dim(x))/prod(shape[-ind])
    return(array(x,shape))
}

以下是它在控制台中的工作原理

> npreshape(1:10,c(-1,5))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10