Save each element of a list to text file

梦想的初衷 提交于 2019-12-11 08:30:57

问题


I have a folder with many csv files. I read them like this

files <-  list.files(pattern = "*.csv")
  [1] "ETo_1980.csv" "ETo_1981.csv" "ETo_1982.csv" "ETo_1983.csv" "ETo_1984.csv" "ETo_1985.csv"
  [7] "ETo_1986.csv" "ETo_1987.csv" "ETo_1988.csv" "ETo_1989.csv" "ETo_1990.csv" "ETo_1991.csv"
  [13] "ETo_1992.csv" "ETo_1993.csv" "ETo_1994.csv" "ETo_1995.csv" "ETo_1996.csv" "ETo_1997.csv"
  [19] "ETo_1998.csv" "ETo_1999.csv" "ETo_2000.csv" "ETo_2001.csv" "ETo_2002.csv" "ETo_2003.csv"
  [25] "ETo_2004.csv" "ETo_2005.csv" "ETo_2006.csv" "ETo_2007.csv" "ETo_2008.csv" "ETo_2009.csv"
  [31] "ETo_2010.csv" "ETo_2011.csv" "ETo_2012.csv" "ETo_2013.csv" "ETo_2014.csv" "ETo_2015.csv

Now I read them:

DT <- lapply(files, fread)

Each file, I want to save as a text file (.txt). How can I save each file as .txt with the same name?

lapply(DT, function(x) { write.table()})?

回答1:


I generated a list named x containing two objects named a and b. Use paste0 in a loop to automatically name the text files like this: a.txt and b.txt. write.table performs the actual saving of the files.

x <- list(a=c(1,2), b=c(3,4))

for(i in 1:length(x)){
  write.table(x[[i]], paste0(names(x)[i], ".txt"), col.names = F)
}

Use list.files to see if the files have been saved in your working directory.

list.files()
[1] "a.txt" "b.txt"



回答2:


Try using read.csv to read in the CSV files, then write.csv to write them:

lapply(files, function(x) {
    df <- read.csv(file=x)
    name <- sub("\\.csv$", "\\.txt", x)
    write.csv(df, file=name)
})



回答3:


Loop over an index instead and create a vector of the filenames you want to save as:

txt_files <- sub("csv$","txt",files)
lapply(seq_along(DT), function(x) write.table(DT[[x]], txt_files[x]))

Beware, that you might want to also exclude row.names from the output too.



来源:https://stackoverflow.com/questions/51893525/save-each-element-of-a-list-to-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!