I am working on a project to compile information from hundreds of email campaigns into one dataset. The platform we use makes us export the data for each action into separate CSVs, and there are three actions we are interested in, meaning we have three CSVs for each campaign. Here’s an example with the naming convention:
Campaign_1_Delivered
Campaign_1_Opened
Campaign_1_Clicked
(If using a different naming convention helps with the solution, I can definitely rename)
There will eventually be hundreds of campaigns, and I’ve kept the naming convention going, just increasing the number by one for the next campaign (e.g., Campaign_2_Delivered, Campaign_3_Delivered, and so on to, currently, Campaign_112_Delivered). All CSV files have the same six columns, regardless of which data type they are:
Member ID, Email Address, First Name, Last Name, Activity, Date
For each campaign, I’d like to load in the CSVs, run some recodes, then merge them into one dataset for the whole campaign. Rather than copy the code hundreds of times then find and replace the numbers, I’m hoping there’s a loop I can run that will just run through the code then do it again but with all the numbers increased by one.
Here’s the first part of the script, for Campaign 23:
`Campaign_23_Delivered <- read.csv(“Campaign 23 – Delivered.csv”)
Campaign_23_Opened <- read.csv(“Campaign 23 – Opened.csv”)
Campaign_23_Clicked <- read.csv(“Campaign 23 – Clicked.csv”)
Campaign_23_Delivered$Campaign_23_DateTime_Delivered <- mdy_hm(Campaign_23_Delivered$Date)
Campaign_23_Delivered$Campaign_23_Delivered <- 1
Campaign_23_Delivered <- Campaign_23_Delivered[c(“Member.ID”, “Campaign_23_Delivered”, “Campaign_23_DateTime_Delivered”)]
Campaign_23_Opened$Campaign_23_DateTime_Opened <- mdy_hm(Campaign_23_Opened$Date)
Campaign_23_Opened$Campaign_23_Opened <- 1
Campaign_23_Opened <- Campaign_23_Opened[c(“Member.ID”, “Campaign_23_Opened”, “Campaign_23_DateTime_Opened”)]
Campaign_23_Clicked$Campaign_23_DateTime_Clicked <- mdy_hm(Campaign_23_Clicked$Date)
Campaign_23_Clicked$Campaign_23_Clicked <- 1
Campaign_23_Clicked <- Campaign_23_Clicked[c(“Member.ID”, “Campaign_23_Clicked”, “Campaign_23_DateTime_Clicked”)]
Campaign_23 <- merge(Campaign_23_Delivered, Campaign_23_Opened, by = “Member.ID”, all.x = TRUE)
Campaign_23 <- merge(Campaign_23, Campaign_23_Clicked, by = “Member.ID”, all.x = TRUE)`
I’ve found several questions and answers for loops, but none that allow me to adjust the number in the dataset AND in the column names like this. In other words, I’d like to run this whole set of code again, but with every instance of 23 replaced with 24, then 25, then 26, and so on.
Any help would be greatly appreciated!
Christopher K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.