简体   繁体   English

数据框:循环参与者/观察并将列写入文本文件

[英]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!) 我试图遍历数据帧中的参与者,然后将不同的列(文本)写入各个.txt文件,以便最终我为每个参与者最终得到一个.txt文件,其中包含他们产生的所有文本(一个参与者可以有几个观测行!)

Searching stackoverflow, this is what I have so far: 搜索stackoverflow,这是我到目前为止的内容:

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. 它在循环产生单个文本文件(.txt)的范围内起作用,但是它们包含part_id,而不是文本。

Any help is welcome and much appreciated! 欢迎任何帮助,不胜感激!

因为在write.table(i, file_path)您正在将i (即part_id )写入文件,所以将其更改为write.table(subset[i], file_path)完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM