简体   繁体   中英

Write.table using looped variable in a for loop

I have a very stupid question. It has been already asked, but none of the solutions provided seem to work with me. I am looping over a list containing different data frames, to perform an analysis and save an output file named differently for each input data frame. The name would be something like originalname_output.txt. I wrote this piece of code which seems to work fine (does all the analysis in the correct ways), but gives an error when coming to the write.table part.


library(qqman)
library(QuASAR)

list_QuASAR <- list (Fw, Rv, tot) #all of the are dfs

for (i in list_QuASAR){
  output <- fitQuasarMpra(i[,2], i[,3], i[,4])
  print(sum(output$padj_quasar<0.1))
  qq(output$pval3, col = "black", cex = 1)
  write.table(output, paste0("quasar_output/", i, "_output.txt"), col.names = T, sep = "\t")
}

fitQuasarMpra is a function of a package called QuASAR. Of course the subdirectory called quasar_output already exists.

The error I am getting is:

Error in file(file, ifelse(append, "a", "w")) : 
  invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :
  the condition has length > 1 and only the first element will be used

I know it's a trivial problem but I am currently stuck. I may consider to switch and use lapply, but then I may encounter the same problem and I wanted to solve this first. Many thanks for you help.

You're trying to use a data frame object ( i ) as part of a file name; ie the data frame itself, not its name. You could try iterating over a named list instead:

list_QuASAR <- list (Fw = Fw,Rv = Rv,tot = tot)

for (i in names(list_QuASAR)){
  output <- fitQuasarMpra(list_QuASAR[[i]][,2], list_QuASAR[[i]][,3], list_QuASAR[[i]][,4])
  print(sum(output$padj_quasar<0.1))
  qq(output$pval3, col = "black", cex = 1)
  write.table(output, paste0("quasar_output/", i, "_output.txt"), col.names = T, sep = "\t")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM