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

    

posted @ 2017-12-16 07:13  emanlee  阅读(201)  评论(0编辑  收藏  举报