R newbie:如何从一组坐标向量创建一个数组?

时间:2013-02-06 23:02:23

标签: r vector multidimensional-array coordinates

假设我在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中思考”太长时间了:基本上我想要做的就是将coordinates分配给一个数组,我认为不能在R中做。 / p>

3 个答案:

答案 0 :(得分:1)

# 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

答案 1 :(得分:1)

或者,这也可能有所帮助。请澄清您想要的结果:))

# 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

答案 2 :(得分:0)

 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