cey
cey

Reputation: 159

How to Filter a Column of a Data Frame Based on an List?

For example I have a data frame like df1 and I splitted it into 5 parts as in z

set.seed(123)
df1 <- data.frame(x = c("A","C","B","D","E","F","G","H","L","K","P","T") ,y = runif(12))
df1

p <- 5
n <- nrow(df1)
z <- split(df1, cummax(as.numeric(gl(p, n%/%p, n))))

And I have other data frame df2 :

df2 <- data.frame(
    emp_name = c("A","B","C","D","E"),
    salary = c(623.3,515.2,611.0,729.0,843.25))

Now I want to filter df2$emp_name based on x values in z. For example, I want to filter df2$emp_name based on x values in z[["1"]]

If z was a data frame I know that I can use filter <- subset(df2, emp_name %in% z$x) but I don't know how to do it where z is a list instead of a data frame.

Thanks and appreciating your response.

Upvotes: 1

Views: 90

Answers (1)

ainsuotain
ainsuotain

Reputation: 308

Actually, here is an answer but not cool

library(dplyr)

for(vi in 1:length(z)){
  print(subset(df2, df2$emp_name %in% z[[vi]]$x))
}

If you want to get every result, make a null list

Upvotes: 1

Related Questions