Nested ifelse statement

前端 未结 9 1226
逝去的感伤
逝去的感伤 2020-11-22 04:02

I\'m still learning how to translate a SAS code into R and I get warnings. I need to understand where I\'m making mistakes. What I want to do is create a variable which summ

9条回答
  •  死守一世寂寞
    2020-11-22 04:22

    With data.table, the solutions is:

    DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign", 
            ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]
    

    The ifelse is vectorized. The if-else is not. Here, DT is:

        idnat     idbp
    1  french mainland
    2  french   colony
    3  french overseas
    4 foreign  foreign
    

    This gives:

       idnat     idbp   idnat2
    1:  french mainland mainland
    2:  french   colony overseas
    3:  french overseas overseas
    4: foreign  foreign  foreign
    

提交回复
热议问题