Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract array from array

Tags:

arrays

r

I wish to extract an array from an array. Here is a small example array, my.array2:

x = cbind(1:5, 6:10, 12:16)
y = cbind(c(11,3,12,14,15), c(16,8,15,17,20), 6:10)
z = cbind(c(21,21,22,3,25), c(26,28,25,8,20), 36:40)

my.array  <- array(c(x, y), dim = c(5, 3, 2))
my.array2 <- array(c(my.array, z), dim = c(5, 3, 3))
my.array2
, , 1

     [,1] [,2] [,3]
[1,]    1    6   12
[2,]    2    7   13
[3,]    3    8   14
[4,]    4    9   15
[5,]    5   10   16

, , 2

     [,1] [,2] [,3]
[1,]   11   16    6
[2,]    3    8    7
[3,]   12   15    8
[4,]   14   17    9
[5,]   15   20   10

, , 3

     [,1] [,2] [,3]
[1,]   21   26   36
[2,]   21   28   37
[3,]   22   25   38
[4,]    3    8   39
[5,]   25   20   40

I wish to extract the rows in which the first column is 3 and the second column is 8 resulting in this array:

, , 1

     [,1] [,2] [,3]
[1,]    3    8   14

, , 2

     [,1] [,2] [,3]
[1,]    3    8    7

, , 3

     [,1] [,2] [,3]
[1,]    3    8   39

and then this data.frame:

     [,1] [,2] [,3]
[1,]    3    8   14
[2,]    3    8    7
[3,]    3    8   39

Here are a couple of attempts that failed:

my.array2[my.array2[,1,] == 3 & my.array2[,2,] == 8,,]

my.array2[my.array2[,1,] == 3 & my.array2[,2,] == 8,my.array2[,1,] == 3 & my.array2[,2,] == 8,my.array2[,1,] == 3 & my.array2[,2,] == 8]

I would prefer a solution in base R.

like image 221
Mark Miller Avatar asked Aug 19 '26 21:08

Mark Miller


1 Answers

Using R: extract matrix from array, using a matrix of indices to get elements from the array, we can do the following:

df = apply(my.array2, 2, as.vector)
# Select rows which meet criteria
df = data.frame(df[df[,1] == 3 & df[,2] == 8, ])
> df
  X1 X2 X3
1  3  8 14
2  3  8  7
3  3  8 39
like image 177
NM_ Avatar answered Aug 22 '26 11:08

NM_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!