89_Simple
89_Simple

Reputation: 3805

Save each element of a list to text file

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()})?

Upvotes: 1

Views: 1245

Answers (3)

milan
milan

Reputation: 4970

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"

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

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)
})

Upvotes: 1

James
James

Reputation: 66834

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.

Upvotes: 1

Related Questions