Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. COL
  2. AABC1
  3. AAAABD2
  4. AAAAAABF3
  5.  
  6. COL NEW_COL
  7. AABC1 T1
  8. AAAABD2 T2
  9. AAAAAABF3 T3
  10.  
  11. CLASS NEW_COL
  12. BC T1
  13. BD T2
  14. BF T3
  15.  
  16. DF <- data.frame(COL = c("AABC1",
  17. "AAAABD2",
  18. "AAAAABF3"),
  19. stringsAsFactors = FALSE)
  20.  
  21. lookup_tbl <- data.frame(CLASS = c("BC", "BD", "BF"),
  22. NEW_COL = c("T1", "T2", "T3"),
  23. stringsAsFactors = FALSE)
  24.  
  25. library(dplyr)
  26. DF %>%
  27. mutate(CLASS = gsub(paste0("^.*(",
  28. paste0(lookup_tbl[["CLASS"]], collapse = "|"),
  29. ").*$"),
  30. "\1",
  31. lookup_tbl[["CLASS"]])) %>%
  32. # or inner_join as required
  33. left_join(lookup_tbl, by = "CLASS")
  34.  
  35. library(tidyverse)
  36.  
  37. lookup_table <- data.frame(
  38. row.names = c('BC', 'BD', 'BF'),
  39. new_col = c('T1', 'T2', 'T3'),
  40. stringsAsFactors = FALSE)
  41.  
  42. lookup <- function(x, table) {
  43. for (class in rownames(table)) {
  44. if (grepl(class, x)) {
  45. return(table[class, 'new_col'])
  46. }
  47. }
  48. }
  49.  
  50. data_frame(col = c('AABC1', 'AAAABD2', 'AAAAAABF3')) %>%
  51. rowwise %>% mutate(new_col = lookup(col, lookup_table))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement