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

后端 未结 2 877
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:33

    Here's a solution that works on each column successively using lapply():

    as.data.frame(lapply(example,function(col) lookup$letter[match(col,lookup$number)]));
    ##   a b c
    ## 1 A E A
    ## 2 B D D
    ## 3 C C C
    ## 4 D B B
    ## 5 E A E
    

    Alternatively, if you don't mind switching over to a matrix, you can achieve a "more vectorized" solution, as a matrix will allow you to call match() and index lookup$letter just once for the entire input:

    matrix(lookup$letter[match(as.matrix(example),lookup$number)],nrow(example));
    ##      [,1] [,2] [,3]
    ## [1,] "A"  "E"  "A"
    ## [2,] "B"  "D"  "D"
    ## [3,] "C"  "C"  "C"
    ## [4,] "D"  "B"  "B"
    ## [5,] "E"  "A"  "E"
    

    (And of course you can coerce back to data.frame via as.data.frame() afterward, although you'll have to restore the column names as well if you want them, which can be done with setNames(...,names(example)). But if you really want to stick with a data.frame, my first solution is probably preferable.)

提交回复
热议问题