Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. ind1<-rep(c("E","W"), times=20)
  2. ind2<-sample(100:150, 40)
  3. y<-c(1:40)
  4. index<-data.frame(cbind(ind1, ind2, y))
  5.  
  6. x1<-sample(c("E","W","N"), 40, replace=TRUE)
  7. x2<-sample(100:150, 40)
  8. x3<-rep(0, times=40)
  9. data<-data.frame(cbind(x1,x2,x3))
  10.  
  11. index1<-split(index, index$ind1)
  12. data1<-split(data, data$x1)
  13. data1$E$x3<-match(data1$E$x2, index1$E$ind2)
  14. data1$W$x3<-match(data1$W$x2, index1$W$ind2)
  15.  
  16. merge(data, index, by.x=c("ind1", "ind2"), by.y=c("x1", "x2"), all.x=TRUE, all.y=FALSE)
  17.  
  18. new_data <- data
  19.  
  20. new_data$x3 <- ifelse(
  21. is.na(match(paste(data$x1, data$x2), paste(index$ind1, index$ind2))),
  22. 0,
  23. index$y)
  24.  
  25. require(dplyr)
  26. left_join(data, index, by = c("x1" = "ind1", "x2" = "ind2"))
  27.  
  28. #Write the row number of index in x3 which matches
  29. data$x3 <- match(interaction(data[c("x1", "x2")]), interaction(index[c("ind1","ind2")]))
  30.  
  31. #In case you want to return 0 instead of NA for nomatch
  32. data$x3 <- match(interaction(data[c("x1", "x2")]), interaction(index[c("ind1","ind2")]), nomatch=0)
  33.  
  34. #Instead of >interaction< you could also use paste as already suggested by Dinre
  35. data$x3 <- match(paste(data$x1, data$x2), paste(index$ind1, index$ind2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement