簡體   English   中英

Output 格式為 R

[英]Output formatting in R

我是 R 的新手,並試圖對多組數據進行一些相關性分析。 我能夠進行分析,但我想弄清楚我的數據結果如何 output 。 我想要 output 如下所示:

 NAME,COR1,COR2
 ....,....,....
 ....,....,....

如果我可以將這樣的文件寫入 output,那么我可以根據需要對其進行后期處理。 我的處理腳本如下所示:

run_analysis <- function(logfile, name)
{
  preds <- read.table(logfile, header=T, sep=",")

  # do something with the data: create some_col, another_col, etc.

  result1 <- cor(some_col, another_col)
  result1 <- cor(some_col2, another_col2)

  # somehow output name,result1,result2 to a CSV file
 }

args <- commandArgs(trailingOnly = TRUE)
date <- args[1]
basepath <- args[2]
logbase <- paste(basepath, date, sep="/")
logfile_pattern <- paste( "*", date, "csv", sep=".")
logfiles <- list.files(path=logbase, pattern=logfile_pattern)

for (f in logfiles) {
  name = unlist(strsplit(f,"\\."))[1]
  logfile = paste(logbase, f, sep="/")
  run_analysis(logfile, name)
}

有沒有一種簡單的方法可以創建一個空白數據框,然后逐行添加數據?

您是否查看過 R 中用於將數據寫入文件的函數? 例如, write.csv 也許是這樣的:

rs <- data.frame(name = name, COR1 = result1, COR2 = result2)
write.csv(rs,"path/to/file",append = TRUE,...)

我喜歡將 foreach 庫用於此類事情:

library(foreach)

run_analysis <- function(logfile, name) {
  preds <- read.table(logfile, header=T, sep=",")
  # do something with the data: create some_col, another_col, etc.
  result1 <- cor(some_col, another_col)
  result2 <- cor(some_col2, another_col2)

  # Return one row of results.
  data.frame(name=name, cor1=result1, cor2=result2)
}

args <- commandArgs(trailingOnly = TRUE)
date <- args[1]
basepath <- args[2]
logbase <- paste(basepath, date, sep="/")
logfile_pattern <- paste( "*", date, "csv", sep=".")
logfiles <- list.files(path=logbase, pattern=logfile_pattern)

## Collect results from run_analysis into a table, by rows.
dat <- foreach (f=logfiles, .combine="rbind") %do% {
  name = unlist(strsplit(f,"\\."))[1]
  logfile = paste(logbase, f, sep="/")
  run_analysis(logfile, name)
}

## Write output.
write.csv(dat, "output.dat", quote=FALSE)

這樣做是在每次調用run_analysis ,將它們綁定到一個名為dat的表中(調用foreach.combine="rbind"部分會導致r bind )。 然后你可以使用write.csv來獲得你想要的 output。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM