Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- COL
- AABC1
- AAAABD2
- AAAAAABF3
- COL NEW_COL
- AABC1 T1
- AAAABD2 T2
- AAAAAABF3 T3
- CLASS NEW_COL
- BC T1
- BD T2
- BF T3
- DF <- data.frame(COL = c("AABC1",
- "AAAABD2",
- "AAAAABF3"),
- stringsAsFactors = FALSE)
- lookup_tbl <- data.frame(CLASS = c("BC", "BD", "BF"),
- NEW_COL = c("T1", "T2", "T3"),
- stringsAsFactors = FALSE)
- library(dplyr)
- DF %>%
- mutate(CLASS = gsub(paste0("^.*(",
- paste0(lookup_tbl[["CLASS"]], collapse = "|"),
- ").*$"),
- "\1",
- lookup_tbl[["CLASS"]])) %>%
- # or inner_join as required
- left_join(lookup_tbl, by = "CLASS")
- library(tidyverse)
- lookup_table <- data.frame(
- row.names = c('BC', 'BD', 'BF'),
- new_col = c('T1', 'T2', 'T3'),
- stringsAsFactors = FALSE)
- lookup <- function(x, table) {
- for (class in rownames(table)) {
- if (grepl(class, x)) {
- return(table[class, 'new_col'])
- }
- }
- }
- data_frame(col = c('AABC1', 'AAAABD2', 'AAAAAABF3')) %>%
- rowwise %>% mutate(new_col = lookup(col, lookup_table))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement