This is my data set
aa <- c(1,NA,NA,NA,NA)
bb <- c(2,1,NA,NA,NA)
cc <- c(5,NA,NA,1,2)
df <- data.frame(group,aa,bb,cc)
group aa bb cc
1 1 1 2 5
2 1 NA 1 NA
3 2 NA NA NA
4 2 NA NA 1
5 2 NA NA 2
where, I have to give variable names to the columns
category<-"group"
A<-"aa"
B<-"bb"
C<-"cc"
I want to replace the NA values by 0 in column "aa", where, group !=1, but I have to use the variables A and category instead
The output would look like
group aa bb cc
1 1 1 2 5
2 1 NA 1 NA
3 2 0 NA NA
4 2 0 NA 1
5 2 0 NA 2
I have tried:
library(dplyr)
library(tidyverse)
df %>%
mutate_at(.vars = A, .funs = funs(if_else(category!= 1 & is.na(.), 0, .)))
, it is not working
Note: The above output was obtained using
df %>%
mutate_at(.vars = A, .funs = funs(if_else(group != 1 & is.na(.), 0, .)))
(I have to use "category" instead of "group")