Search code examples
rfor-loopdataframerowswritefile

Data frame: loop over participants/observations and write column to text file


I'm trying to loop over the participants in a data frame and then write a different column (text) to individual .txt files, so that I ultimately end up with one .txt file per participant containing all the text they produced (a participant can have several observations rows!)

Searching stackoverflow, this is what I have so far:

dataframe <- data.frame(part_id = rep(seq(1:3), 2), text = c("test1", 
"test2", "test3", "test4", "test5", "test6"))
dataframe <- dataframe %>% arrange(part_id)

for(i in dataframe$part_id) {
    subset[i] <- dataframe[dataframe$part_id == i,]$text
    write.table(i, paste(i, ".txt", sep=""), 
                col.names = FALSE, row.names = FALSE,  sep = "\t")
}

It works insofar as the loop produces individual text files (.txt), but instead of the text, they contain the part_id.

Any help is welcome and much appreciated!


Solution

  • Because in write.table(i, file_path) you're writing i (which is the part_id) into the file, change it to write.table(subset[i], file_path) will do the work.