0

I´m a newbie in R (and program). There are some examples with one or two "[", but I could not be sure, what they means.

dim(data)[[-1]] # means the column number of a data frame
dim(data)[-1]   # what does it mean?
samples[,dim(samples)[[2]],2] # what does this mean?

Thanks a lot for your help!

Bettina10
  • 23
  • 1
  • 6

1 Answers1

0

In case data is stored in object of class data.frame, matrix or array, dim() returns a numeric vector containing size of each dimension. So the subsetting operator is simply applied to that vector. The operations you described can be used more generally. Here is explanation of what those exactly do.

Let vec <- dim(data)

vec[-1] - drops the first element similar to vec[2:length(vec)]

vec[[-1]] - same as above in your example, but is usually used in context of data.frames and lists. Here is an example that demonstrates the difference:

dt <- data.frame(a = rnorm(20), b = rnorm(20))
dt[-1]    # returns data.frame with only b column
dt[[-1]]  # returns numeric vector containing values of b column

samples[, dim(samples)[[2]], 2] - this syntax is more often use for selecting dimensions in an array (matrix with more than rows and columns) and will return a numeric vector that contains all rows in last column of the third dimension. Can play with the following to see for yourself:

array <- array(data = rnorm(8), dim = c(2, 2, 2))
array[, dim(array)[[2]], 2]

Note: Plz provide example data so we don't have to guess what objects are or replicate it.

Aleh
  • 776
  • 7
  • 11
  • Thank you Aleh. The samples is something from this code: `samples <- array(0, dim = c(length(rows), lookback / step, dim(data)[[-1]]))` – Bettina10 Feb 21 '18 at 10:38
  • Ok that explains the last one. You can also subset data.frames with [a, b, c] by only a and b will be used. – Aleh Feb 21 '18 at 11:38