Search code examples
rdplyr

Mutate a column if certain columns are all NA


I have the dataframe below

df = structure(list(HHID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13), strata = c("Urban", "Rural", "Rural", "Urban", "Rural", 
"Rural", "Urban", "Urban", "Rural", "Rural", "Urban", "Rural", 
"Urban"), rand = c(23145, 13755, 17890, 25634, 56231, 96541, 
23654, 52361, 74125, 96124, 37851, 85321, 64123), empl = c(1000, 
1750, 480, 630, 1200, 1000, 1700, 500, 300, 0, 400, 900, NA), 
    agric = c(750, 650, 400, 400, 0, 750, 0, 0, 750, 0, 300, 
    900, NA), loans = c(0, 350, 300, 0, 0, 1200, 500, 250, 500, 
    0, 700, 0, NA), assets = c(500, 0, 0, 0, 700, 0, 0, 500, 
    150, 0, 500, 750, NA), remittances = c(0, 200, 1500, 1250, 
    0, 500, 700, 900, 1200, 0, 1000, 0, NA), govt_aid = c(0, 
    0, 1200, 1000, 0, 0, 0, 900, 1300, 0, 800, 0, NA), hum_aid = c(0, 
    0, 800, 1200, 0, 0, NA, 1400, 1500, 0, 200, 1100, NA), check = c(0L, 
    0L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L)), row.names = c(NA, 
-13L), class = c("tbl_df", "tbl", "data.frame"))

and would like to replace the column check to NA if the columns empl all through to hum_aid are all NA Any help will be greatly appreciated.


Solution

  • Any of the following and many more would work:

    df %>% 
       mutate(check = check*NA^if_all(empl:hum_aid, is.na))
    

    df %>%
       mutate(check = `is.na<-`(check, if_all(empl:hum_aid, is.na)))
    

    df %>%
       mutate(check = if_else(if_all(empl:hum_aid, is.na), NA, check))
    

    df %>%
        mutate(check = ifelse(!rowSums(!is.na(pick(empl:hum_aid))), NA, check))
    

    results:

    # A tibble: 13 × 11
        HHID strata  rand  empl agric loans assets remittances govt_aid hum_aid check
       <dbl> <chr>  <dbl> <dbl> <dbl> <dbl>  <dbl>       <dbl>    <dbl>   <dbl> <int>
     1     1 Urban  23145  1000   750     0    500           0        0       0     0
     2     2 Rural  13755  1750   650   350      0         200        0       0     0
     3     3 Rural  17890   480   400   300      0        1500     1200     800     1
     4     4 Urban  25634   630   400     0      0        1250     1000    1200     1
     5     5 Rural  56231  1200     0     0    700           0        0       0     0
     6     6 Rural  96541  1000   750  1200      0         500        0       0     0
     7     7 Urban  23654  1700     0   500      0         700        0      NA     0
     8     8 Urban  52361   500     0   250    500         900      900    1400     1
     9     9 Rural  74125   300   750   500    150        1200     1300    1500     1
    10    10 Rural  96124     0     0     0      0           0        0       0     0
    11    11 Urban  37851   400   300   700    500        1000      800     200     0
    12    12 Rural  85321   900   900     0    750           0        0    1100     0
    13    13 Urban  64123    NA    NA    NA     NA          NA       NA      NA    NA