0

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.

stefan
  • 90,330
  • 6
  • 25
  • 51
bear_525
  • 41
  • 5

2 Answers2

3

If your dataset is called dataset and if I understood it correctly, this should work:

filenames <- paste0(dataset$IDs, ".txt")

lapply(filenames, file.create)
Leon Samson
  • 405
  • 3
  • 12
1

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"
stefan
  • 90,330
  • 6
  • 25
  • 51