Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply subset function to a list of dataframes

I have a list of SpatialPolygonDataFrame that I can assimilate to dataframe like this:

df.1 <- data.frame(A = c(1:10), B = c(1, 2, 2, 2, 5:10))
df.2 <- data.frame(A = c(1:10), B = c(1, 2, 2, 2, 2, 2, 7:10))
df.3 <- data.frame(A = c(1:10), B = c(1, 2, 2, 4:10))

list.df <- list(df.1, df.2, df.3)

I would like to get a list of a subset of each dataframe based on condition (list.df.sub is the result I am looking for):

df.1.sub <- subset(df.1, df.1$B != 2)
df.2.sub <- subset(df.2, df.2$B != 2)
df.3.sub <- subset(df.3, df.3$B != 2)

list.df.sub <- list(df.1.sub, df.2.sub, df.3.sub)

I would like to apply directly my subset on list.df. I know that I have to use lapply function but don't know how?

like image 310
DJack Avatar asked Dec 03 '22 21:12

DJack


2 Answers

This should work:

lapply(list.df, function(x)x[x$B!=2,])

or with subset:

lapply(list.df, subset, B!=2)
like image 189
user1981275 Avatar answered Dec 24 '22 19:12

user1981275


If you only want to subset one column, you can also use the "[[" function

example_list <- list(iris, iris, iris)
lapply(example_list, "[[", "Species")
like image 45
Jeff Bezos Avatar answered Dec 24 '22 20:12

Jeff Bezos