Recode a variable using data.table package

后端 未结 3 1899
名媛妹妹
名媛妹妹 2021-01-27 16:10

If I want to recode a variable in R using data.table, what is the syntax? I saw some ans but didn\'t find them appropriate.

e.g. if I have the variable cal

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 16:32

    Once you have a data.table then it would be most efficient to use a vectorized translation strategy. The match function provides a method of creating a "selection vector" for a choosing a item from a set of character possibilities:

    library(data.table)
    setDT(trips)  # create a data.table from a dataframe
    
    trips[ , Gender := c("Unknown", "male", "Female")[match(Gender, c(0,1,2))] ]
    #-------------------
    > trips
         Name  Gender
    1:   John    male
    2:   Tina  Female
    3:   Dave  Female
    4: Casper Unknown
    

    For this specific case, a simpler solution could be (ht to @Chinsoon):

    trips[, gender := c("Unknown", "Male", "Female")[gender + 1L] ]
    

提交回复
热议问题