我想知道R中是否有函数可以帮助我处理问题匹配函数,如果两个数据集有重复值会创建吗?
例如,
x=c(1,2,2,3,3)
y=c(2,2,3)
我希望将所有2,2,3,3保留在X中,但只列出Y中的2,2,3,我仍然希望它们按顺序排列。
有办法吗?
答案 0 :(得分:0)
x[which(x %in% y)]
y[which(y %in% x)]
答案 1 :(得分:0)
#crate some objects to match
x<-data.frame(fruits = c("apples", "bananas", "oranges", "apples"), values = c(1,2,3,4))
y<-data.frame(fruits = c("apples", "oranges", "bananas"), colors = c("red", "pink", "green" )
# x$color will be the new column in x with relevant values from y
# ifelse is a simple condition - if a fruit is found in y, it gets the color from y, if there is nothing to match, it gets an NA
x$color<-ifelse(x$fruits %in% y$fruits,as.character(y$colors), NA)
x