I would like to export content from cells in a dataframe into separate html files. I would also like to name the files according to the corresponding cell in another column, but cannot make it work.
I am using a for loop to export each cell into an html file, and it works, but I cannot make it grab the appropriate filename from another cell.
Example dataframe:
names <- c("alpha", "beta", "gamma", "delta", "epsilon")
content <- c(paste("<div>Example", 1:5, "</div>"))
df <- data.frame(names, content)
This is my for loop, but I need to grab the corresponding data from df$names:
for (x in df$content) {
filename <- # the corresponding row in df$names + ".html"
writeLines(x, filename)
}
The expectable outcome is to end up with five html files with the corresponding content in the working folder named:
alpha.thml,
beta.html,
etc.
2
Answers
I found out that which() can help me find the corresponding index number. I post my self-answer.
With a for-loop you are better off looping over indices and use those for subsetting:
There are also
*apply
,purrr::*map
andpurrr::*walk()
families, this particular case is well suited forpwalk()
, iterate over multiple lists in parallel (columns in data.frame) for a side effect (writing files):Resulting files:
Created on 2024-06-28 with reprex v2.1.0