Change values in multiple columns of a dataframe using a lookup table

后端 未结 2 875
Happy的楠姐
Happy的楠姐 2020-12-06 20:13

I am trying to change the value of a number of columns at once using a lookup table. They all use the same lookup table. I know how to do this for just one column -- I\'d ju

2条回答
  •  无人及你
    2020-12-06 20:45

    Using dplyr

    f <- function(x)setNames(lookup$letter, lookup$number)[x] 
    library(dplyr)
    example %>% 
      mutate_each(funs(f))
    #  a b c
    #1 A E A
    #2 B D D
    #3 C C C
    #4 D B B
    #5 E A E
    

    Or with data.table

    library(data.table)
    setDT(example)[, lapply(.SD, f), ]
    #   a b c
    #1: A E A
    #2: B D D
    #3: C C C
    #4: D B B
    #5: E A E
    

提交回复
热议问题