MariKo
MariKo

Reputation: 305

Save data from loop in txt file

I have a data frame EEG:

Description   Onset    Run
Neut_inc      3.7416   Run1
Neut_inc      4.3636   Run1
Reward        4.48     Run2
Neut_inc      5.7416   Run2
Neut_inc      6.72     Run3
Neut_inc      7.7416   Run3
Reward        8.96     Run3

My goal is to subset all Neut_inc conditions per run and save them in separate .txt files for each Run, so the .txt file after I read it in would look like this:

> Run1 
Description   Onset    Run
Neut_inc      6.72     Run3
Neut_inc      7.7416   Run3

I wrote a code that is looping through all runs, however it saves .txt file only with the last run.

for(run_number in unique(EEG$Run)){
    run <- subset(EEG[which(EEG$Run == run_number),])
    Neut_con <- subset(run[which(run$Run == run_number),], Description %in% c("Neut_con"))  

write.table(Neut_con, file ="C:/Users/EXPERIMENTS/onsets/Neut_con.txt",row.names=FALSE, quote = FALSE, sep = "\t")  

}

How should I change the code?

Upvotes: 0

Views: 1132

Answers (1)

Austin
Austin

Reputation: 326

for(run_number in unique(EEG$Run)){
    run <- subset(EEG[which(EEG$Run == run_number),])
    Neut_con <- subset(run[which(run$Run == run_number),], Description %in% c("Neut_con"))  

    write.table(Neut_con, file =paste0("C:/Users/EXPERIMENTS/onsets/Neut_con_", run_number, ".txt"),row.names=FALSE, quote = FALSE, sep = "\t")  

}

The problem is you are writing one file and then overwriting it every time you go through the loop. By adding the paste0() function, you make the file name dynamic so that you have file1, file2, file3, et cetera. This way you don't overwrite the file each time.

Upvotes: 1

Related Questions