Reputation: 657
I am creating a set of PDFs that each include different information. I want to name the files according to the people who will be receiving the information. I am using for
loops to run this:
for (i in 1:nrow(files)){
rmarkdown::render(input = "files_script.Rmd",
output_format = "pdf_document",
output_file = paste("Information_", i, ".pdf", sep=''),
output_dir = "directoryname/")
}
The script works just fine, but the output files are simply numbered in my directory. I'd like to name them according to names in a column of my dataframe.
My data looks like this:
Feedback Name Surname
xyz John Smith
abc Karen Jones
I'd like to name the files by surname.
Upvotes: 0
Views: 49
Reputation: 12478
So your names are in two columns in a data.frame (I called it df here). You could use the for
loop like this:
for (name in paste0(df$Name, "_", df$Surname)) {
rmarkdown::render(input = "files_script.Rmd",
output_format = "pdf_document",
output_file = paste0("Information_", name, ".pdf"),
output_dir = "directoryname/")
}
I replaced paste(sep = "")
with paste0()
since it is doing the same thing.
Not sure though why you would do it that way. files_script.Rmd is always the same file. So it would be faster to render it once and then just change the name.
Since you said you want to keep the i
as for loop variable, here is how you can do that:
names <- paste0(df$Name, "_", df$Surname)
for (i in seq_along(names)) {
rmarkdown::render(input = "files_script.Rmd",
output_format = "pdf_document",
output_file = paste0("Information_", names[i], ".pdf"),
output_dir = "directoryname/")
}
seq_along
is a safer way of doing 1:length(names)
in this case (see this)
Upvotes: 2