Adding a column based on another column R data.table

前端 未结 3 1502
时光取名叫无心
时光取名叫无心 2020-12-22 08:33

I have two data tables in R:

#install.packages(\"data.table\")
library(data.table)
dt1 <- data.table(Num = c(1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,5,5,5         


        
相关标签:
3条回答
  • 2020-12-22 08:59

    We can join with using on

    library(data.table)#v1.9.6+
    dt2[dt1, on ="Num"]
    

    For creating the "Letter" column in "dt1", we don't need the "dt2"

    dt1[, Letter:= LETTERS[Num]]
    
    0 讨论(0)
  • 2020-12-22 09:06
    setkey(dt1, Num)
    setkey(dt2, Num)
    dt2[dt1]
        Num Letter
     1:   1      A
     2:   1      A
     3:   1      A
     4:   2      B
     5:   2      B
    
    0 讨论(0)
  • 2020-12-22 09:07

    The disadvantage of the methods in the other answers is that dt1 is not updated and the result is only printed to the console. You can update dt1 by reference as follows:

    dt1[dt2, lttr := Letter, on="Num"]
    

    This gives the following result:

    > dt1
        Num lttr
     1:   1    A
     2:   1    A
     3:   1    A
     4:   2    B
     5:   2    B
     6:   2    B
     7:   2    B
     8:   3    C
     9:   3    C
    10:   3    C
    11:   3    C
    12:   3    C
    13:   3    C
    14:   4    D
    15:   4    D
    16:   4    D
    17:   4    D
    18:   4    D
    19:   4    D
    20:   4    D
    21:   5    E
    22:   5    E
    23:   5    E
    
    0 讨论(0)
提交回复
热议问题