Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
- 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)
- merge(data, index, by.x=c("ind1", "ind2"), by.y=c("x1", "x2"), all.x=TRUE, all.y=FALSE)
- new_data <- data
- new_data$x3 <- ifelse(
- is.na(match(paste(data$x1, data$x2), paste(index$ind1, index$ind2))),
- 0,
- index$y)
- require(dplyr)
- left_join(data, index, by = c("x1" = "ind1", "x2" = "ind2"))
- #Write the row number of index in x3 which matches
- data$x3 <- match(interaction(data[c("x1", "x2")]), interaction(index[c("ind1","ind2")]))
- #In case you want to return 0 instead of NA for nomatch
- data$x3 <- match(interaction(data[c("x1", "x2")]), interaction(index[c("ind1","ind2")]), nomatch=0)
- #Instead of >interaction< you could also use paste as already suggested by Dinre
- data$x3 <- match(paste(data$x1, data$x2), paste(index$ind1, index$ind2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement