I'd like to create a folder of empty .txt files that correspond to values of the ID column. I plan to add details to these text files one by one over time. There are thousands of these IDs.
Here is an example:
IDs | People |
---|---|
124 | Jim |
345 | Mary |
675 | Hilary |
897 | Chris |
235 | John. |
I want the name of the text files to be 124.txt, 345.txt, 675.txt, etc and all saved in a folder that I can retrieve in R.
I tired to use the cat function cat(text, file = "myfile.txt") but I don't know how to automate the name of the files to be taken from the column values.
One option would be to use a for
loop:
dat <- data.frame(
stringsAsFactors = FALSE,
IDs = c(124L, 345L, 675L, 897L, 235L),
People = c("Jim", "Mary", "Hilary", "Chris", "John.")
)
path <- tempdir()
for (id in dat$IDs) {
text <- as.character(id)
cat(text, file = file.path(path, paste0(id, ".txt")))
}
dir(path, "\\.txt")
#> [1] "124.txt" "235.txt" "345.txt" "675.txt" "897.txt"