zoukankan      html  css  js  c++  java
  • How do I extract a single column from a data.frame as a data.frame


    Say I have a data.frame:

    df <- data.frame(A=c(10,20,30),B=c(11,22,33), C=c(111,222,333))
      A  B  C
    1 10 11 111
    2 20 22 222
    3 30 33 333

    If I select two (or more) columns I get a data.frame:

    x <- df[,1:2]
       A  B
     1 10 11
     2 20 22
     3 30 33

    This is what I want. However, if I select only one column I get a numeric vector:

    x <- df[,1]
    [1] 1 2 3

    ===================
    Use drop=FALSE

    > x <- df[,1, drop=FALSE]
    > x
       A
    1 10
    2 20
    3 30

    From the documentation (see ?"[") you can find:

        If drop=TRUE the result is coerced to the lowest possible dimension.
        
        
        
        
    ===================
    Omit the ,:

    x <- df[1]

       A
    1 10
    2 20
    3 30

    From the help page of ?"[":

        Indexing by [ is similar to atomic vectors and selects a list of the specified element(s).

    A data frame is a list. The columns are its elements.

     
    ===================
    REF:

    https://stackoverflow.com/questions/21025609/how-do-i-extract-a-single-column-from-a-data-frame-as-a-data-frame

        

  • 相关阅读:
    OCA读书笔记(11)
    shell命令--rev
    OCA读书笔记(10)
    shell命令--cut
    OCA读书笔记(9)
    shell命令--tail
    天气的研究
    网络知识汇总(2)
    shell命令--head
    OCM读书笔记(2)
  • 原文地址:https://www.cnblogs.com/emanlee/p/8045742.html
Copyright © 2011-2022 走看看