celestialgod

data.table non-equi join

Mar 16th, 2017
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.38 KB | None | 0 0
  1. library(data.table)
  2.  
  3. judgeDF <- data.table(x_lb = c(1, 4, 7), x_ub = c(3, 6, 9),
  4.                       y_cate = paste0("M", 1:3), output = paste0("K", 1:3))
  5. judgeDF
  6. #    x_lb x_ub y_cate output
  7. # 1:    1    3     M1     K1
  8. # 2:    4    6     M2     K2
  9. # 3:    7    9     M3     K3
  10.  
  11. input <- unique(data.table(X = sample(1:10, 100, TRUE),
  12.                            Y = sample(paste0("M", 1:3), 100, TRUE)))
  13. head(input)
  14. #     X  Y
  15. # 1:  3 M2
  16. # 2: 10 M3
  17. # 3:  4 M3
  18. # 4:  3 M1
  19. # 5:  6 M3
  20. # 6:  6 M2
  21.  
  22. judgeDF[input, .(X, Y, output), on = .(x_lb <= X, x_ub >= X, y_cate == Y)]
  23. #     X  Y output
  24. # 1:  3 M2     NA
  25. # 2: 10 M3     NA
  26. # 3:  4 M3     NA
  27. # 4:  3 M1     K1
  28. # 5:  6 M3     NA
  29. # 6:  6 M2     K2
  30.  
  31. judgeDF <- data.frame(x_lb = c(1, 4, 7), x_ub = c(3, 6, 9),
  32.                       y_cate = paste0("M", 1:3), output = paste0("K", 1:3),
  33.                       stringsAsFactors = FALSE)
  34. input <- unique(data.frame(X = sample(1:10, 100, TRUE),
  35.                            Y = sample(paste0("M", 1:3), 100, TRUE),
  36.                            stringsAsFactors = FALSE))
  37. output <- rep(NA_character_, nrow(input))
  38. for (i in 1L:nrow(input)) {
  39.   loc <- which(input[i, 1] >= judgeDF[, 1] & input[i, 1] <= judgeDF[, 2] &
  40.                  input[i, 2] == judgeDF[, 3])
  41.   if (length(loc) > 0L) {
  42.     output[i] <- judgeDF[loc, 4]
  43.   } else {
  44.     output[i] <- NA_character_
  45.   }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment