简体   繁体   English

从R中的循环返回单独的txt文件

[英]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. 额外信息:该循环适用于每个单独的播放器(具有不同的ID),可通过adehabitatLT包中的as.ltraj()获得数据。

(i know there are similar questions on this forum but none could help me in solving this problem) (我知道这个论坛上有类似的问题,但是没有一个可以帮助我解决这个问题)

Maybe you should add 1:length(traject) in your for loop as in: 也许您应该在for循环中添加1:length(traject) ,如下所示:

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)) 您的循环仅返回一个迭代(最后一个),因为您的索引仅是length(traject)而您应该使用1:length(traject)来使索引i从第一个元素一直移动到最后一个,您也可以用seq_len(length(traject))替换1:length(traject) seq_len(length(traject))

As @Jilber pointed out, you are only iterating over a single number. 正如@Jilber指出的那样,您只需要迭代一个数字。

Just for reference: If you want to iterate over all items in a vector or list, you can simply do 仅供参考:如果要遍历向量或列表中的所有项目,只需执行

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

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

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