簡體   English   中英

R newbie:如何從一組坐標向量創建一個數組?

[英]R newbie: how to create an array from a set of coordinate vectors?

假設我在3D空間的不同位置進行了一組測量。 測量的位置具有坐標向量

x <- c(0,1,2,3)
y <- c(4,5,6)
z <- c(7,8)

因此,例如,最接近原點的測量在位置= (0,4,7) 從上面的坐標向量,我想創建一個3D數組 - 只有一個數組。 @bnaul:這些是體素中心的坐標,我想為其分配值。 我的意圖是,在pcode中,

arr <- magic( c(0,1,2,3) , c(4,5,6) , c(7,8) )
# arr is now a 3D array filled with NAs
value1 -> arr[0, 4, 7]
value2 -> arr[3, 5, 7]
# and so on, but if one does
valueBad -> arr[4,3,2] # one should get an error, as should, e.g.,
valueBad2 -> arr[3,4,5]

但是我懷疑我一直在“在NetCDF中思考”太長時間了:基本上我想要做的就是為數組分配坐標 ,我不相信R可以做到這一點。

# starting data
x <- c(0,1,2,3)
y <- c(4,5,6)
z <- c(7,8)

# find every combo
w <- expand.grid( x , y , z )

# convert to a matrix
v <- as.matrix( w )

# view your result
v

或者,這也可能有所幫助。 請澄清你想要的結果:)

# starting data
x <- c(0,1,2,3)
y <- c(4,5,6)
z <- c(7,8)

# create a 4 x 3 x 2 array
v <- 
    array( 
        # start out everything as missing..
        NA , 
        # ..and make the lengths of the dimensions the three lengths.
        dim = 
            c( length( x ) , length( y ) , length( z ) ) 
    )

# view your result
v

# now populate it with something..
# for now, just populate it with 1:24
v[ , , ] <- 1:length(v)

# view your result again
v
 array(NA, dim=c(4,3,2), 
   dimnames=list( x = c(0,1,2,3),
     y = c(4,5,6),
     z = c(7,8) ) )
, , z = 7

   y
x    4  5  6
  0 NA NA NA
  1 NA NA NA
  2 NA NA NA
  3 NA NA NA

, , z = 8

   y
x    4  5  6
  0 NA NA NA
  1 NA NA NA
  2 NA NA NA
  3 NA NA NA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM