Write many files in a for loop

后端 未结 2 421
醉梦人生
醉梦人生 2020-11-27 19:14

I have sample data like this

df <- data.frame(name = rep(letters[1:7], each = 24), salary = runif(24*7, 100, 200))

I wanted to separate

相关标签:
2条回答
  • 2020-11-27 19:44

    Try this,

    for (ii in names(lst)){
      filename <- paste(ii, ".txt", sep="")
      write.table(lst[[ii]], filename, col.names=FALSE,row.names=FALSE,sep="\t",quote=FALSE)
    }
    
    0 讨论(0)
  • 2020-11-27 19:49

    Given your lst, the following will write this out to a series of TXT files with names equal to the name of lst, plus .txt:

    lapply(names(lst),
           function(x, lst) write.table(lst[[x]], paste(x, ".txt", sep = ""),
                                        col.names=FALSE, row.names=FALSE, sep="\t", 
                                        quote=FALSE),
           lst)
    

    To modify your for() loop, try:

    for(i in seq_along(lst)) {
        write.table(lst[[i]], paste(names(lst)[i], ".txt", sep = ""), 
                    col.names = FALSE, row.names = FALSE, sep = "\t", quote = FALSE)
    }
    

    The problem was trying to or assuming R would paste together the filenames for you.

    0 讨论(0)
提交回复
热议问题