R匹配2个以上的条件并返回响应值 [英] R matching more than 2 conditions and return the response value

查看:240
本文介绍了R匹配2个以上的条件并返回响应值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据集,第一个是一组索引:

Hi I have two data set where the first one is a set of index:

ind1<-rep(c("E","W"), times=20)
ind2<-sample(100:150, 40)
y<-c(1:40)
index<-data.frame(cbind(ind1, ind2, y))

第二个数据集是需要索引的数据集.

The second data set is the one needs to be indexed.

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中指出data中的x1x2分别与index中的ind1ind2匹配,并返回相应的y.

I would like indicate in x3 where the x1 and x2 in data to be matched with ind1 and ind2 in index respectively and return the corresponding 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.我哪部分做错了? 谢谢.

It kinda matched the way I wanted but did not return y correctly. Which part I did wrong? Thanks.

还有,这样做有更快/更智能的方法吗?因为我可能有更多条件要匹配.最初,我尝试了if else语句,但是没有用.

Also, is there a faster/smarter way of doing it? Because I might have more conditions to match with. Originally I tried if else statement but didn't work.

推荐答案

merge(data, index, by.x=c("ind1", "ind2"), by.y=c("x1", "x2"), all.x=TRUE, all.y=FALSE)

将为ind1ind2以及x1x2的每个匹配组合提供xy值. x1x2的所有组合都会保留(即使index中不会出现ind1ind2的组合,但不会出现ind1ind2的组合按照说明,解决方案将保留x3y值,但是如果您想删除y值,则可以按照@ Ferdinand.kraft使用merge(data[ ,-3], ....的建议.

will give you the x and y values for each matching combination of ind1 and ind2, and x1 and x2. All combinations of x1 and x2 will be kept (even if that combination of ind1 and ind2 doesn't occur in index, but combinations of ind1 and ind2 that don't occur in data will be dropped. As written, the solution will keep x3 and y values, but if you'd like to drop the y values you can use merge(data[ ,-3], ... as per @Ferdinand.kraft 's suggestion.

这篇关于R匹配2个以上的条件并返回响应值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆