写一个循环的输出

时间:2015-11-17 01:08:06

标签: r loops

我在数千个文件中运行一个循环来执行Pagel Lambda

files <- list.files(pattern=".txt")
column_names <- data.frame(files = "files", V1 = "V1", Lambda = "lamda", LogL = "logL", LogL10 = "logL10", pvalue = "P")
write.table(column_names, file = "output.csv", row.names = FALSE, 
            append = FALSE, col.names = FALSE, sep = ", ", quote = TRUE)

for(i in files){
  graph <- read.table(i,header=F)
  row.names(graph)<-graph[,1]
  trait<-graph[,-1]
  names(trait)<-row.names(graph)
  result <- data.frame(t(c(files[i], phylosig(mytree, trait, method="lambda", test=TRUE, nsim=999))))
  write.table(result, file = "output.csv", row.names = FALSE, 
              append = TRUE, col.names = FALSE, sep = ", ")
}

我的目标是为每个输入文件获得一个输出文件,其中包含1行的结果。 我的变量 result 如下所示:

[1] "some data in x given as 'NA', dropping corresponding species from tree"
             V1       lambda      logL     logL0 P
1 EOG7B0F7J.txt 6.610696e-05 -59.62533 -59.62509 1

我需要这些值在输出文件中和输入文件的名称(我在循环中没有设置它,我不知道怎么做)

所以我希望输出看起来像这样:

FileA  V1       lambda      logL     logL0 P
FileB V1       lambda      logL     logL0 P
FileC V1       lambda      logL     logL0 P

或类似的东西 - 如果有人可以帮我解决这个问题,我会非常高兴。

非常感谢

1 个答案:

答案 0 :(得分:1)

我明白了,如果有人感兴趣,这里就是答案:

column_names <- data.frame(i = "files", Lambda = "lamda", LogL = "logL", LogL10 = "logL10", pvalue = "P")
                           write.table(column_names, file = "output.csv", row.names = FALSE, 
                           append = FALSE, col.names = FALSE, sep = ", ", quote = TRUE)

for(i in files){
  graph <- read.table(i,header=F)
  row.names(graph)<-graph[,1]
  trait<-graph[,-1]
  names(trait)<-row.names(graph)
  result <- data.frame(t(c(i, phylosig(mytree, trait, method="lambda", test=TRUE, nsim=999))))
  my.df <- data.frame(lapply(result, as.character), stringsAsFactors=FALSE)
  write.table(my.df, file = "output.csv", row.names = FALSE, append = TRUE, col.names = FALSE, sep = ", ")
}