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

后端 未结 3 1060
夕颜
夕颜 2020-12-16 15:56

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

相关标签:
3条回答
  • 2020-12-16 16:13

    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"
    
    0 讨论(0)
  • 2020-12-16 16:16

    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"
    
    0 讨论(0)
  • 2020-12-16 16:21

    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.

    0 讨论(0)
提交回复
热议问题