グリッドn上にあるフィールドの観測が100x100あり、このデータが単一の vector として格納されているとしobsます。何が事前なの100x100xnかわからないまま、これを配列に変形したいと思います。nmatlabで使用できます
reshape(obs,100,100,[]);
またはパイソンで
np.reshape(obs,(100,100,-1))
R に同様の機能がありますか、それとも最後のインデックスのサイズを手動で計算する必要がありますか?
グリッドn上にあるフィールドの観測が100x100あり、このデータが単一の vector として格納されているとしobsます。何が事前なの100x100xnかわからないまま、これを配列に変形したいと思います。nmatlabで使用できます
reshape(obs,100,100,[]);
またはパイソンで
np.reshape(obs,(100,100,-1))
R に同様の機能がありますか、それとも最後のインデックスのサイズを手動で計算する必要がありますか?
これを試してください(さらなるニーズに合わせて調整できると確信しています):
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
    これはあなたが欲しいものですか?
 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]
    上記の 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