I'm sure this is pretty easy to do, but I can't work it out at the moment.
I want to add to a regression formula based on whether a variable is a 1
in a binary variable. Something like this, but it would be for many variables. What is a good way of doing this? Ideally this would involve a purrr
function.
library(tidyverse)
set.seed(2)
df <- tibble(a = sample(c(1,0), 6, replace = TRUE),
b = sample(c(1,0), 6, replace = TRUE))
df_desired <- df %>%
mutate(vars = if_else(a == 1, "a", ""),
vars = if_else(b == 1, paste0(vars, " + b"), ""),
vars = str_remove(vars, "^ \\+ "),
vars = paste("y ~", vars))
# A tibble: 6 × 3
a b vars
<dbl> <dbl> <chr>
1 1 1 "y ~ a + b"
2 1 1 "y ~ a + b"
3 0 1 "y ~ b"
4 0 0 "y ~ " # maybe ignore this row
5 0 1 "y ~ b"
6 0 1 "y ~ b"