R函数在数据框中的一列中搜索数据框中另一列的元素
R function to search one column in a dataframe for elements from another column in a dataframe
我正在尝试在数据框 Test1 中创建一个新列,如果列 Fruit 中的元素存在于数据框 Test2 中,该列的值为 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)
}
}
你可以试试这个:
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
我正在尝试在数据框 Test1 中创建一个新列,如果列 Fruit 中的元素存在于数据框 Test2 中,该列的值为 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)
}
}
你可以试试这个:
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