繁体   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