Vinay billa
Vinay billa

Reputation: 309

Subset dataframes stored in a list

I have a list containing 16 dataframes all of which have only two columns

DateTime    Value 
2009-05-31    100
2009-06-30    200
2009-07-31    300 
and so on 

I want to subset all the dataframes in the list based on a date filter. I tried the following code but it did not work out

> c <- function(df) {
+ within(df, DateTime >= "2009-06-30")
+ }
> train_data <- lapply(my_data, c)

Am I missing out on something here ?

Thank You.

Upvotes: 0

Views: 50

Answers (3)

thepule
thepule

Reputation: 1751

Try this (assuming the Datetime columns in your data frames are formatted as Dates):

c <- function(df){
df[df$DateTime >= as.Date("2009-06-30"),]
}

train_data <- lapply(my_data, c)

Or if you want to use with:

c <- function(df){
with(df, df[DateTime >= "2009-06-30",])
}

Upvotes: 1

datahero
datahero

Reputation: 101

You have a subset method:

new_df = subset(df, DateTime > "2009-06-30")

The output will be:

    DateTime Value
3 2009-07-31   300

Upvotes: 0

Vinay billa
Vinay billa

Reputation: 309

Nevermind guys, I found the answer

training_data <- lapply(my_data, subset, DateTime >= "2009-06-30")

Upvotes: 0

Related Questions