How to keep a column of dataframe as dataframe

后端 未结 2 500
北荒
北荒 2021-01-18 09:53

Question: how to extract a column of dataframe and keep its structure as unchanged?

data <- iris
data[, 1] ##this will be a vector and will lose the name          


        
相关标签:
2条回答
  • 2021-01-18 10:41

    Use list subsetting which will return a data frame:

    data[1]
    

    Produces

      Sepal.Length
    1          5.1
    2          4.9
    3          4.7
    4          4.6
    5          5.0
    6          5.4
    # ... omitted rows
    

    When you use only one argument to [ with data frames it subsets data frames as lists, where each column is an element. It also preserves attributes, so the subset of the data frame is also a data frame.

    0 讨论(0)
  • 2021-01-18 10:46

    data[, 1, drop = FALSE] will do the trick.

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