Giora Simchoni
Giora Simchoni

Reputation: 3689

R: equivalent to Numpy's "dot dot dot" operator for slicing

In Python, if a is a Numpy array, I can do:

a[..., 0]

To get the first element of the last dimension, no matter the shape of a.

Example:

a = np.array([1,2,3])
a[..., 0]
Out[128]: array(1)

a = np.array([[1,2,3],[4,5,6]])
a[..., 0]
Out[130]: array([1, 4])

a = np.array([[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]]])
a[..., 0]
Out[132]: 
array([[ 1,  4],
       [ 7, 10]])

Didn't find an equivalent in base R here.

Is there a way to do this in (base) R to any array? Can really be helpful in generic functions which receive any nD array.

Upvotes: 0

Views: 473

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269854

We could write our own. Here a must be an array or an object such that as.array(obj) is an array and i is an optional index into the last dimension defaulting to 1.

last <- function(a, i = 1) {
  a <- as.array(a)
  ix <- lapply(dim(a), seq_len)
  ix[[length(ix)]] <- i
  do.call("[", c(list(a), ix))
}


# tests

a <- array(1:24, 2:4)
last(a)

m <- matrix(1:6, 2)
last(m)

last(1:3)

last(as.matrix(BOD))      # BOD is a builtin data.frame

Upvotes: 1

Related Questions