Nested ifelse statement

前端 未结 9 1230
逝去的感伤
逝去的感伤 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:33

    Using the SQL CASE statement with the dplyr and sqldf packages:

    Data

    df <-structure(list(idnat = structure(c(2L, 2L, 2L, 1L), .Label = c("foreign", 
    "french"), class = "factor"), idbp = structure(c(3L, 1L, 4L, 
    2L), .Label = c("colony", "foreign", "mainland", "overseas"), class = "factor")), .Names = c("idnat", 
    "idbp"), class = "data.frame", row.names = c(NA, -4L))
    

    sqldf

    library(sqldf)
    sqldf("SELECT idnat, idbp,
            CASE 
              WHEN idbp IN ('colony', 'overseas') THEN 'overseas' 
              ELSE idbp 
            END AS idnat2
           FROM df")
    

    dplyr

    library(dplyr)
    df %>% 
    mutate(idnat2 = case_when(.$idbp == 'mainland' ~ "mainland", 
                              .$idbp %in% c("colony", "overseas") ~ "overseas", 
                             TRUE ~ "foreign"))
    

    Output

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

提交回复
热议问题