【问题标题】:R function to search one column in a dataframe for elements from another column in a dataframe [duplicate]R函数在数据框中的一列中搜索数据框中另一列的元素[重复]
【发布时间】:2020-11-05 09:48:59
【问题描述】:

如果数据框 Test2 中存在 Fruit 列中的元素,我正在尝试在数据框 Test1 中创建一个新列,该列的值为 1。我已经使用了 exists() 和 %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)
  }
} 

【问题讨论】:

    标签: r list loops if-statement exists


    【解决方案1】:

    你可以试试这个:

    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
    

    【讨论】:

    • 谢谢!它总是比我尝试让它更容易哈哈
    • @AllisonKline 太好了!如果您对这个答案感到满意,请接受它!
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    相关资源
    最近更新 更多