Eric Kaschalk
Eric Kaschalk

Reputation: 369

R creating a list using variable columns from df

I'm looking for the cleanest way to implement the following.

vars <- c("f1", "f2", "f3")
list(data$f1, data$f2, data$f3)

Where instead I make the list by using each string in vars instead of hardcoding the data$f1, data$f2, ...

It can be solved easily using a for loop to create the list but is there a one-liner/lapply way to solve it?

Upvotes: 1

Views: 41

Answers (1)

Sam Dickson
Sam Dickson

Reputation: 5239

If data is a dataframe, then it's already a list. You can do this:

data[,vars]

Or you can make it a simple list:

c(data[,vars])

Upvotes: 2

Related Questions