Joeri
Joeri

Reputation: 167

Returning separate txt files from loop in R

I want to return the results of each iteration in a loop to be written in a separate text file, but for some reason it does not seem to work. My code is:

 for (i in length(traject)){        
      player <-subset(traject[[i]],subset=(dt==1),)
      test<-player  
      write.table(test, file=paste(i, "test.txt", sep=" "))
      head(test)
       }

Which only return the last iteration, what do i do wrong to produce the results of all iterations in separate text files?

Extra info: The loop is for each separate player (with different ID's) to gain data via as.ltraj() from the adehabitatLT package.

(i know there are similar questions on this forum but none could help me in solving this problem)

Upvotes: 2

Views: 163

Answers (2)

Ricardo Saporta
Ricardo Saporta

Reputation: 55420

As @Jilber pointed out, you are only iterating over a single number.

Just for reference: If you want to iterate over all items in a vector or list, you can simply do

 for (i in traject) {
  #....
 } 

Upvotes: 0

Jilber Urbina
Jilber Urbina

Reputation: 61214

Maybe you should add 1:length(traject) in your for loop as in:

for (i in 1:length(traject)){   do something }

Your loop is only returning one iteretion (the last one) because your index is just length(traject) instead you should use 1:length(traject) for the index i to move from the first element all the way to the last one, you can also replace 1:length(traject) by seq_len(length(traject))

Upvotes: 4

Related Questions