Recode a variable using data.table package

后端 未结 3 1934
名媛妹妹
名媛妹妹 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:21

    You can do it this way

    library(data.table)
    trips <- data.table(Name=c('John','Tina','Dave','Casper'),gender=c(1,2,1,0))
    trips[,gender:= ifelse(gender == 0 , "Unknown", 
                            ifelse(gender == 1 ,  "Male", 
                                                  "Female" ))]
    

    Two problems in your code:

    • You need to use := which is the assigning symbol for a column in data.table
    • You can only have one alternative with ifelse, so you need another ifelse for the third case: if gender is not 0 then you need to test if gender is 1 to separate the Male and Female cases

提交回复
热议问题