0

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")

rire
  • 1
  • See the marked dupe or the package vignette [Programming with dplyr](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html) for how to use dynamic column names in `dplyr` functions. – Gregor Thomas Oct 27 '20 at 14:58
  • what is your aim? Why do you need a variable? Are you trying to write a function? – Onyambu Oct 27 '20 at 14:59
  • Good old base R: `df[[A]] <- ifelse(is.na(df[[A]]) & df[[category]] != 1, 0, df[[A]])` – s_baldur Oct 27 '20 at 15:03
  • if at all you are not interested in a function, this does not seem to be meaningful. Although still doable: `df%>%mutate_at(get('A'), ~if_else(get(category) != 1 & is.na(.), 0, .))` – Onyambu Oct 27 '20 at 15:08
  • @sindri_baldur you note that if `A<-c("aa","bb")` the method you have wont work. – Onyambu Oct 27 '20 at 15:10
  • **IF**. In any case the base R solution could then be wrapped with lapply. – s_baldur Oct 27 '20 at 15:12

0 Answers0