0

I'm trying to create a new column in dataframe Test1 that has a 1 if an element from the column Fruit exists in dataframe Test2. I've used exists() and %in%, I know it's more about the way I built the loop (new to loops and if statements) so any help appreciated!

Fruit<- c("Blueberry", "Pomegranate", "Apple")
Test2<- data.frame(Fruit)

Fruit<- c("Apple", "Orange", "Banana", "Pomegranate", "Blueberry", "Rasberry")
Number<-c(1,5,12,15, 6, 7)

Test1<- data.frame(Fruit, Number)


Test1$presence<- for (i in Test2$Fruit) {
  
  if ( is.element(i, Test1$Fruit)){
    print(1)
 
  } else{
    print(0)
  }
} 

1 Answers1

0

You can try this:

Test1$Presence <- as.numeric(Test1$Fruit %in% Test2$Fruit)

        Fruit Number Presence
1       Apple      1        1
2      Orange      5        0
3      Banana     12        0
4 Pomegranate     15        1
5   Blueberry      6        1
6    Rasberry      7        0
Duck
  • 39,058
  • 13
  • 42
  • 84