Recode NA as another value with some conditions

recode_na_if(df, grouping_cols = NULL, target_groups = NULL, replacement = 0)

Arguments

df

A data.frame object with missing values

grouping_cols

Character columns to use for grouping the data

target_groups

Character Recode NA as if and only if the grouping column is in this vector of values

replacement

Values to use to replace NAs for IDs that meet the requirements. Defaults to 0.

Examples

some_data <- data.frame(ID=c("A1","A2","A3", "A4"),
A=c(5,NA,0,8), B=c(10,0,0,1),C=c(1,NA,NA,25))
# Replace NAs with 0s only for IDs in A2 and A3
recode_na_if(some_data,"ID",c("A2","A3"),replacement=0)
#> # A tibble: 4 x 4
#>   ID        A     B     C
#>   <chr> <dbl> <dbl> <dbl>
#> 1 A1        5    10     1
#> 2 A2        0     0     0
#> 3 A3        0     0     0
#> 4 A4        8     1    25