1

I have a bunch of txt-files and want to write a loop that reads the whole respective file and writes its content (as a single string) to a dataframe. Here's the code:

file.names <- dir(path, pattern = "*.txt", recursive = TRUE, full.names = TRUE) 

df1 <- data.frame(matrix(ncol = 1, nrow = 0))
colnames(df1) <- "string"


for(i in 1:length(file.names)){
df2 <- read_file(file.names[i])
dataframe <- rbind(df1, df2)
}

The loop doesn't work - I only read one file and write its content as the name of the column. I want the string content of every txt-file to represent one observation/row in the dataframe. Thanks a lot for your time and effort!

1 Answers1

1

What I would do is read the data.frames into a list. Using do.call we can combine everything into one data.frame which is ready to be processed further.

file.names <- dir(path, pattern = "*.txt", recursive = TRUE, full.names = TRUE) 

xy <- lapply(file.names, FUN = read_file)
xy <- do.call(rbind, xy)

This code assumes that read_file returns a proper data.frame with all identical column names.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197