John Huang
John Huang

Reputation: 845

Selecting a column in a list of dataframes

I have a list of dataframes and I would like to select a specific column in those dataframes to work with.

 plot_list <- lapply(plot_list, subset,
                          subset = format(DateAndTime, "%Y") == year)

In this line of code I would like to select the column DateAndTime from the dateframes in the list plot_list. What would be the most efficient way of doing this?

Upvotes: 0

Views: 55

Answers (2)

Ashish Baid
Ashish Baid

Reputation: 533

result<-lapply(plot_list, function(x) x[,'DateAndTime'])

Upvotes: 1

dcarlson
dcarlson

Reputation: 11046

Here is a reproducible example that you can adapt to your data:

data(iris)   # Measurements on three species of iris
iris.list <- split(iris, iris$species)   # Create a list of data frames
SL <- lapply(iris.list, "[", "Sepal.Length")   # Pull out the Sepal.Length measurements
str(SL)
# List of 3
#  $ setosa    :'data.frame':   50 obs. of  1 variable:
#   ..$ Sepal.Length: num [1:50] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#  $ versicolor:'data.frame':   50 obs. of  1 variable:
#   ..$ Sepal.Length: num [1:50] 7 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 ...
#  $ virginica :'data.frame':   50 obs. of  1 variable:
#   ..$ Sepal.Length: num [1:50] 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 ...

Upvotes: 1

Related Questions