将R循环的输出写入文件 [英] Write output of R loop to file

查看:721
本文介绍了将R循环的输出写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我的R循环(请参见下文)在每次迭代期间都会覆盖自身.我想将每个循环的结果输出到文本文件中.

Currently my R loop (see below) overwrites itself during each iteration. I want to output the result from each loop into a text file.

更详细地: R初学者在这里想知道如何在脚本中包含一行,以便将为每个文件计算的平均值写入文本文件.因此,脚本将创建一个新的空文本文件,然后每次脚本计算文件中第4列的平均值时,该值将输出到文本文件中的一行,该行包含column1中的文件名和Column1中的平均值专栏2. 感谢您的帮助!

In more detail: R beginner here wondering how to include a line in my script so that the mean value calculating for each file is written to a text file. So that the script creates a new empty text file and then each time the script calculates the mean of column 4 in a file that value is output to a row in the text file which contains the name of the file in column1 and the mean value in column 2. Thanks for your help!

filename <- system("ls /dir/",intern=TRUE)

for(i in 1:length(filename)){

file <- read.table(filename[i],header=FALSE) ## if you have headers in your files ##
mean <- mean(as.numeric(file$V4))



}

推荐答案

要在循环运行时执行此操作,请在循环中添加:

To do it as the loop is running, in your loop add:

write.csv(data.frame(fname=filename[i],mean=mean),file="output.csv",append=TRUE)

但是,这将意味着很多文件系统开销,并且更快地在R中生成整个数据帧,然后将文件整体写入.因此,而不是您的循环编写:

However, this would mean a lot of file system overhead, and it would be quicker the produce the whole data frame in R and then write the file as a whole. So instead of your loop write:

means <- sapply(filename, function(x) mean(as.numeric(read.table(x,header=FALSE)$V4)))

然后使用以下命令将文件整体写入:

And then write the file as a whole with:

write.csv(data.frame(fname=filename,mean=means),file="output.csv")

这篇关于将R循环的输出写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆