Write output of R loop to file

前端 未结 2 1710
一生所求
一生所求 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 02:24

    The following script will do it by first creating the file with only column names, and then appending each result.

    filename <- system("ls /dir/",intern=TRUE)
    
    column_names <- data.frame(filename = "filename", mean = "mean")
    write.table(column_names, file = "output.csv", row.names = FALSE, 
                append = FALSE, col.names = FALSE, sep = ", ", quote = TRUE)
    
    for(i in 1:length(filename)){
      file <- read.table(filename[i],header=FALSE)
      newline <- data.frame(t(c(filename[i], mean(as.numeric(file$V4)))))
      write.table(newline, file = "output.csv", row.names = FALSE, 
                  append = TRUE, col.names = FALSE, sep = ", ")
    }
    

    Writing to the file at each step is not very efficient though, and you might consider doing it at the end only:

    filename <- system("ls /dir/",intern=TRUE)
    
    results <- data.frame(filename = "filename", mean = "mean")
    
    for(i in 1:length(filename)){
      file <- read.table(filename[i],header=FALSE)
      newline <- data.frame(t(c(filename = filename[i], mean = mean(as.numeric(file$V4)))))
      results <- rbind(results, newline)
    }
    write.table(results, file = "output.csv", row.names = FALSE, 
                append = FALSE, col.names = TRUE, sep = ", ")
    

提交回复
热议问题