The "6m" at the end of the variable represents 6 months. Likewise, I want to run this code for 1yr, 18m, and 2yr. Instead of running the code again and again, I want to create a function to overcome this repeated coding. How can I write a function on this?
You cannot build variable names by placing text and variables next to each other. Code like
Var <- "Tuesday"
New_Var <- 6
will not make a new variable named New_Tuesday, no matter how you wrap Var. You can build a variable name from text but I suspect that is not the right approach. Can you post a little of your data? I suspect making it tidy will make your problem much easier. If your data frame is named DF, you can post the first 15 rows by posting the output of
dput(head(DF, 15))
If there are more columns than are needed to demonstrate the problem, you can make a reduced data frame with the select() function and use that in dput().
You will inevitably struggle to compose elegant tidyverse code directly onto data that is un-tidy.
The first goal should be to tidy your data, then the use of tidyverse is a straightforward as can be ...
Likely you need to pivot _longer your data seperating the timeX component of the variable names to an independent variable. 12 Tidy data | R for Data Science (had.co.nz)