Are dataframe[ ,-1] and dataframe[-1] the same?

dataframe, r

Solution

Almost.

`[-1]` uses the fact that a data.frame is a list, so when you do `dataframe[-1]` it returns another data.frame (list) without the first element (i.e. column).

`[ ,-1]`uses the fact that a data.frame is a two dimensional array, so when you do `dataframe[, -1]` you get the sub-array that does not include the first column.

A priori, they sound like the same, but the second case also tries by default to reduce the dimension of the subarray it returns. So depending on the dimensions of your `dataframe` you may get a data.frame or a vector, see for example:

> data <- data.frame(a = 1:2, b = 3:4)
> class(data[-1])
[1] "data.frame"
> class(data[, -1])
[1] "integer"

You can use `drop = FALSE` to override that behavior:

> class(data[, -1, drop = FALSE])
[1] "data.frame"

Problem

Sorry this seems like a really silly question but are `dataframe[ ,-1]` and `dataframe[-1]` the same, and does it work for all data types? And why are they the same

Original source