Recode multiple columns using dplyr

后端 未结 5 845
一向
一向 2020-12-11 19:19

I had a dataframe where I recoded several columns so that 999 was set to NA

dfB <-dfA %>%
  mutate(adhere = if_else(adhere==999, as.numeric(NA), adhere         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 19:47

    I think it is related the column type. I added mutate_if to convert all integer columns to numeric, and then set the recode value to be NA_real_. It seems working.

    library(dplyr)
    
    y <- data.frame(y1=c(1,2,999,3,4), y2=c(1L, 2L, 999L, 3L, 4L), y3=c(T,T,F,F,T))
    
    z <- y %>%
      mutate_if(is.integer, as.numeric) %>%
      mutate_at(vars(y1:y2), funs(recode(.,`999` = NA_real_)))
    z
    #   y1 y2    y3
    # 1  1  1  TRUE
    # 2  2  2  TRUE
    # 3 NA NA FALSE
    # 4  3  3 FALSE
    # 5  4  4  TRUE
    

提交回复
热议问题