dplyr replacing na values in a column based on multiple conditions

后端 未结 2 699
长情又很酷
长情又很酷 2021-01-14 11:07

I have this data with two NA values in the Occupation column and I am trying to use dplyr to replace the values with the word Pensioner

2条回答
  •  悲&欢浪女
    2021-01-14 11:25

    We can use if_else

    data %>%
      mutate(Occupation = if_else(is.na(Occupation) & 
                             Yrs_Empleo <= -999 &
                             Organisation == "XNA", "Pensioner", Occupation))
    #    Yrs_Empleo  Occupation           Organisation          Income_type
    #1      1.7452055    Laborers Business Entity Type 3              Working
    #2      3.2547945  Core staff                 School        State servant
    #3      0.6164384    Laborers             Government              Working
    #4      8.3260274    Laborers Business Entity Type 3              Working
    #5      8.3232877  Core staff               Religion              Working
    #6      4.3506849    Laborers                  Other        State servant
    #7      8.5753425 Accountants Business Entity Type 3 Commercial associate
    #8      1.2301370    Managers                  Other        State servant
    #9  -1000.6657534   Pensioner                    XNA            Pensioner
    #10     5.5315068    Laborers            Electricity              Working
    #11     1.8602740  Core staff               Medicine              Working
    #12 -1000.6657534   Pensioner                    XNA            Pensioner
    #13     7.4438356    Laborers Business Entity Type 2              Working
    

    Or use replace

    data %>% 
       mutate(Occupation = replace(Occupation, 
                 is.na(Occupation) & 
                             Yrs_Empleo <= -999 &
                             Organisation == "XNA",
                   "Pensioner"))
    

提交回复
热议问题