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

        

  • 相关阅读:
    webpack学习(一)—— 入门
    AMD 规范
    CommonJS 规范
    webpack 故障处理
    webpack 开发环境
    webpack 插件
    webpack 配置文件
    webpack 使用
    webpack Loader
    webpack常用的插件安装命令
  • 原文地址:https://www.cnblogs.com/emanlee/p/8045742.html
Copyright © 2011-2022 走看看