Home > Enterprise >  Apply subset to list of dataframes in R
Apply subset to list of dataframes in R

Time:03-11

I have a 9 dataframes with the same column names and from each I need to remove all the rows that have a " " in the column named "Reverse".

for a single dataframe I would do it this way:

df1 <- subset(df1, Reverse !=  " ")

is there a way to do this with all 9 at the same time?

I tried to put them all in a list first and then just use the same code as above but it doesnt work:

df.list <- list(df1, df2, df3, .....)
df.list <- subset(df.list, Reverse !=  " ")

Can someone help me?

CodePudding user response:

You're close, use lapply to iterate a function on each frame:

df.list <- lapply(df.list, function(dat) subset(dat, Reverse != " "))

FYI, especially considering they are all the same basic structure (names, etc), then keeping them in a list makes a lot of sense and I encourage you to stick with df.list instead of individual df1, df2, etc.

  •  Tags:  
  • r
  • Related