celestialgod

map values

Dec 2nd, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.81 KB | None | 0 0
  1. library(data.table)
  2. library(plyr)
  3. library(dplyr)
  4. library(tidyr)
  5. library(magrittr)
  6.  
  7. # data generation
  8. set.seed(100)
  9. dt = data.table(t(replicate(100, sample(letters, 5)))) %>%
  10.   setnames(paste0("id", 1:5))
  11. mapTable = data.table(value = letters, score = sample(1:100, 26))
  12.  
  13. # solution
  14. dt %>% add_rownames %>% tbl_dt %>% gather(id, value, -rowname) %>%
  15.   mutate(score = mapvalues(value, mapTable$value, mapTable$score)) %>%
  16.   group_by(rowname) %>% summarise(med_score = median(score))
  17.  
  18. # Source: local data table [100 x 2]
  19. #
  20. #    rowname med_score
  21. # 1        1        73
  22. # 2        2        40
  23. # 3        3        54
  24. # 4        4        42
  25. # 5        5        43
  26. # 6        6        58
  27. # 7        7        56
  28. # 8        8        38
  29. # 9        9        58
  30. # 10      10        58
  31. # ..     ...       ...
Advertisement
Add Comment
Please, Sign In to add comment