Home > Enterprise >  match elements from a list and a dataframe and create a new dataframe under condition if it matches
match elements from a list and a dataframe and create a new dataframe under condition if it matches

Time:07-29

Hello guys I have a list a dataframe as you see below

listA <- list("Jon", "Maria", "Jon", "Maria", "Ben")
Name <- c("Jon", "Bill", "Tina", "Jon", "Jon")
Age <- c(23, 41, 32, 22, 44)
df <- data.frame(Name, Age)

So what i am trying to achieve is to create an if function that will print

  if (listA[1] == df$Name)
    print(new_df) #under the condition
##for example a new df with all the Jons and their ages

The error I get for something like this is the following because there are more Jons than 1

Error in if (...) print(...) : 
  the condition has length > 1

I understand how this works for numerical values but I am struggling with the strings. My desired output would be for example a new dataframe that will print the following values for example

#if "Jon" is in the list print  new dataframe
Name <- c("Jon", "Jon", "Jon")
Age <- c(23, 22, 44)
new_df <- data.frame(Name2, Age2)

If you understand my question could you please provide me with your help?

CodePudding user response:

You can use

df[which(listA[1] == df$Name), ]

  • output
  Name Age
1  Jon  23
4  Jon  22
5  Jon  44

CodePudding user response:

thelatemail suggested

lapply(listA, \(x) df[df$Name == x,] )

Zheyuan Li suggested

subdf <- df[df$Name %in% unlist(listA), ]
split(subdf, subdf$Name)
  •  Tags:  
  • r
  • Related