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
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
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"
dataframe[-1]
will treat your data in vector form, thus returning all but the very first element [[edit]] which as has been pointed out, turns out to be a column, as a data.frame
is a list
. dataframe[,-1]
will treat your data in matrix form, returning all but the first column.
Sorry, wanted to leave this as a comment but thought it was too big, I just found it interesting that the only one which remains a non integer is dataframe[1].
Further to Carl's answer, it seems dataframe[[1]] is treated as a matrix as well. But dataframe[1] isn't....
But it can't be treated as a matrix cause the results for dataframe[[1]] and matrix[[1]] are different.
D <- as.data.frame(matrix(1:16,4))
D
M <- (matrix(1:16,4))
M
> D[ ,1] # data frame leaving out first column
[1] 1 2 3 4
> D[[1]] # first column of dataframe
[1] 1 2 3 4
> D[1] # First column of dataframe
V1
1 1
2 2
3 3
4 4
>
> class(D[ ,1])
[1] "integer"
> class(D[[1]])
[1] "integer"
> class(D[1])
[1] "data.frame"
>
> M[ ,1] # matrix leaving out first column
[1] 1 2 3 4
> M[[1]] # First element of first row & col
[1] 1
> M[1] # First element of first row & col
[1] 1
>
> class(M[ ,1])
[1] "integer"
> class(M[[1]])
[1] "integer"
> class(M[1])
[1] "integer"