I'm trying to write a function to automate the creation of some new variables using tidyverse tools. I figured out my problem involves tidyeval, but I haven't quite figured out where I went wrong in the code below, which is just reproducing the variable name. As a second step, I'd like to do something besides a for loop to apply the function a bunch of times. I've read enough StackOverflow answers shaming for loops, but I can't find a worked example for using some kind of apply function creating new variables on an existing dataframe. Thanks!
library(tidyverse)
x = c(0,1,2,3,4)
y = c(0,2,4,5,8)
df <- data.frame(x,y)
df
simple_func <- function(x) {
var_name <- paste0("pre_", x, "_months")
var_name <- enquo(var_name)
df <- df %>%
mutate(!! var_name := ifelse(x==y,1,0)) %>%
mutate(!! var_name := replace_na(!! var_name))
return(df)
}
simple_func(1)
#Desired result
temp <- data.frame("pre_1_months" = c(1,0,0,0,0))
temp
bind_cols(df,temp)
#Step 2, use some kind of apply function rather than a loop to apply this function sequentially
nums <- seq(1:10)
for (i in seq_along(nums)) {
df <- simple_func(nums[i])
}
df