1
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

Name2 <- c("Jon", "Jon", "Jon")
Age2 <- c(23, 22, 44)
new_df <- data.frame(Name2, Age2)

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

okay thank you i believe now is making more sense - Dimitris Karditsas
all true please - Dimitris Karditsas
And, in general, don't use a list when a vector will do. In your code it seems like listA <- list("Jon", "Maria", "Jon", "Maria", "Ben") would be better as vecA <- c("Jon", "Maria", "Jon", "Maria", "Ben") - Gregor Thomas
I just need an if statement that will match the same names of a list and a dataframe and then it will show or create a new dataframe under this condition i.e a dataframe with all the Jons and their ages for example - Dimitris Karditsas
@DimitrisKarditsas No wording. Show desired output for your example. - Zheyuan Li