R函数在数据框中的一列中搜索数据框中另一列中的元素

时间:2020-07-15 19:40:00

标签: r list loops if-statement exists

我正在尝试在数据框Test1中创建一个新列,如果数据框Test2中存在“水果”列中的元素,则该列为1。我已经使用过exist()和%in%,我知道它更多地是关于构建循环的方式(对于循环和if语句来说是新的),因此对您有所帮助!

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 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

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