R matching more than 2 conditions and return the response value
match, r
Solution
merge(data, index, by.x=c("ind1", "ind2"), by.y=c("x1", "x2"), all.x=TRUE, all.y=FALSE)
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.
Problem
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)) ``` 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) ``` It kinda matched the way I wanted but did not return `y` correctly. Which part I did wrong? Thanks. 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.