Am trying to use mutate function inside my own created function to in order to deal with DRY principle. Am not sure if it would be possible. Whenever I run the function collapsevars I get the correct answer but the mutate function does not pick the variable name specified in the collapsevars function. Any leads?
The sample code is as below:
library(dplyr)
set.seed(2021)
avars <- c("a1", "a2") # Variables to collapse to a single variable
bvars <- c("b1", "b2") # Variables to collapse to another variable
mydata <- tibble(
a1 = factor(round(runif(20, 1, 3)),
labels = c("Yes", "No", "N/A")),
a2 = factor(round(runif(20, 1, 3)),
labels = c("Yes", "No", "N/A")),
b1 = factor(round(runif(20, 1, 3)),
labels = c("Yes", "No", "N/A")),
b2 = factor(round(runif(20, 1, 3)),
labels = c("Yes", "No", "N/A")),
c1 = round(rnorm(20, 10, 2)))
mydata
mydata <- mydata %>%
mutate(afin = ifelse(rowSums(
select(., all_of(avars)) == "Yes") > 0,
"Yes", "No"),
bfin = ifelse(rowSums(
select(., all_of(bvars)) == "Yes") > 0,
"Yes", "No"))
collapsevars <- function(var, varcollapse){
mydata <- mydata %>%
mutate(var = ifelse(rowSums(
select(., all_of(varcollapse)) == "Yes") > 0,
"Yes", "No"))
}
collapsevars(afin, avars)