Apply subset function to a list of dataframes
10,937
Solution 1
This should work:
lapply(list.df, function(x)x[x$B!=2,])
or with subset
:
lapply(list.df, subset, B!=2)
Solution 2
If you only want to subset one column, you can also use the "[[" function
example_list <- list(iris, iris, iris)
lapply(example_list, "[[", "Species")
Author by
DJack
Updated on June 19, 2022Comments
-
DJack almost 2 years
I have a list of
SpatialPolygonDataFrame
that I can assimilate todataframe
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 uselapply
function but don't know how?