Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a native R syntax to extract rows of an array?

Imagine I have an array in R with N dimensions (a matrix would be an array with 2 dimensions) and I want to select the rows from 1 to n of my array. I was wondering if there was a syntax to do this in R without knowing the number of dimensions. Indeed, I can do

x = matrix(0, nrow = 10, ncol = 2)
x[1:5, ] # to take the 5 first rows of a matrix

x = array(0, dim = c(10, 2, 3))
x[1:5, , ] # to take the 5 first rows of a 3D array

So far I haven't found a way to use this kind of writing to extract rows of an array without knowing its number of dimensions (obviously if I knew the number of dimensions I would just have to put as many commas as needed). The following snippet works but does not seem to be the most native way to do it:

x = array(0, dim = c(10, 2, 3, 4)
apply(x, 2:length(dim(x)), function(y) y[1:5])

Is there a more R way to achieve this?

like image 234
GFabien Avatar asked Feb 12 '21 08:02

GFabien


People also ask

What is dim in Rstudio?

dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame. Syntax: dim(x)


2 Answers

Your apply solution is the best, actually.

apply(x, 2:length(dim(x)), `[`, 1:5)

or even better as @RuiBarradas pointed out (please vote his comment too!):

apply(x, -1, `[`, 1:5)

Coming from Lisp, I can say, that R is very lispy. And the apply solution is a very lispy solution. And therefore it is very R-ish (a solution following the functional programming paradigm).

like image 157
Gwang-Jin Kim Avatar answered Sep 29 '22 01:09

Gwang-Jin Kim


Function slice.index() is easily overlooked (as I know to my cost! see magic::arow()) but can be useful in this case:

x <- array(runif(60), dim = c(10, 2, 3))
array(x[slice.index(x,1) %in% 1:5],c(5,dim(x)[-1]))

HTH, Robin

like image 37
robin hankin Avatar answered Sep 29 '22 02:09

robin hankin