Question

I know that eval() may lead to codes that are hard to maintain, but I run yet again into a case where I don't know what else to use.

Below is the manual way of getting column a from data and create a new data frame.

data <- data.frame(a=1:5, b=6:10)
new.data <- data.frame( a = data[ , "a"] )

This works fine for one column. However, in my real application, I have to extract multiple columns into multiple new data frames, and I must refer to the column by name (hence the title, turning column name (i.e. string) into command). How can I do that without resorting to eval(parse=text)?

Was it helpful?

Solution

Remember that data frames are stored as lists, and lists can be subset with a vector of strings (if the list is named, but the column names are the names of the list elements). So you can just do something like:

> mydf <- data.frame( a=1:5, b=5:1, c=11:15, d=21:25 )
> 
> mycols <- c('a','d')
> 
> mydf[ mycols ]
  a  d
1 1 21
2 2 22
3 3 23
4 4 24
5 5 25
> str(.Last.value)
'data.frame':   5 obs. of  2 variables:
 $ a: int  1 2 3 4 5
 $ d: int  21 22 23 24 25
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top