嗨,我有两个数据集,其中第一个是一组索引:
ind1<-rep(c("E","W"), times=20)
ind2<-sample(100:150, 40)
y<-c(1:40)
index<-data.frame(cbind(ind1, ind2, y))
第二个数据集是需要索引的数据集。
x1<-sample(c("E","W","N"), 40, replace=TRUE)
x2<-sample(100:150, 40)
x3<-rep(0, times=40)
data<-data.frame(cbind(x1,x2,x3))
我想在
x3
中注明哪里x1
和 x2
在 data
配用ind1
和 ind2
在 index
分别返回对应的y
.index1<-split(index, index$ind1)
data1<-split(data, data$x1)
data1$E$x3<-match(data1$E$x2, index1$E$ind2)
data1$W$x3<-match(data1$W$x2, index1$W$ind2)
它有点符合我想要的方式但没有返回
y
正确。我做错了哪一部分?谢谢。
另外,是否有更快/更智能的方法?因为我可能有更多的条件可以匹配。最初我尝试过 if else 语句但没有用。
最佳答案
merge(data, index, by.x=c("ind1", "ind2"), by.y=c("x1", "x2"), all.x=TRUE, all.y=FALSE)
会给你
x
和 y
ind1
的每个匹配组合的值和 ind2
, 和 x1
和 x2
. x1
的所有组合和 x2
将被保留(即使 ind1
和 ind2
的组合不会出现在 index
中,但 ind1
和 ind2
的组合不会出现在 data
中也将被删除。 ,解决方案将保留 x3
和 y
值,但如果您想删除 y
值,您可以根据@Ferdinand.kraft 的建议使用 merge(data[ ,-3], ...
。
关于R匹配2个以上条件并返回响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18319985/