0
votes

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?

1
I'm not sure I totally follow, but lapply(listA, \(x) df[df$Name == x,] ) ? - thelatemail
subdf <- df[df$Name %in% unlist(listA), ]; split(subdf, subdf$Name). Reply in comment with a link to your deleted question? I want to remove my comment there. - Zheyuan Li

1 Answers

0
votes

You can use

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

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