Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a column of dataframe as dataframe

Tags:

dataframe

r

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 of the column in dataframe
like image 867
yliueagle Avatar asked Apr 22 '14 18:04

yliueagle


2 Answers

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

like image 199
Jota Avatar answered Oct 08 '22 23:10

Jota


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.

like image 41
BrodieG Avatar answered Oct 08 '22 21:10

BrodieG