Write output of R loop to file

前端 未结 2 1704
一生所求
一生所求 2021-01-03 01:43

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

In more detail: R beginner here

2条回答
  •  北海茫月
    2021-01-03 01:59

    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)
    

    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")
    

提交回复
热议问题