A.Birdman
A.Birdman

Reputation: 171

set correct column names when output list items to csv in r

Given a list (e.g. out), I want to write each item out to a separate csv file for use elsewhere. The list is large and contains a lot of items so I wanted to shortcut using a for loop. I created the following to build a name for each output file based on the data group and date. When I run it everything works except it renames the columns using the list item name and the existing colnames (e.g. instead of 'week4' I get 'pygweek4'. I do not want it to change my column names.

I tried setting col.names = TRUE, hoping to retain the existing names, and using the code below to specify the names, as well as setting col.names = FALSE. In all cases I get a warning message saying that "attempt to set 'col.names' ignored".

Can anyone suggest a simple method of retaining the column names I already have?

out <- list(pyg = structure(list(week4 = c("0", "1", "1", "0", "1"), 
      week5 = c("0", "1", "1", "1", "1"), week6 = c("0", "1", "0", "1", "1"), 
      week7 = c("0", "0", "0", "1", "1"), week8 = c("0", "1", "0", "1", "1")), 
      row.names = 281:285, class = "data.frame"), 
      saw = structure(list(week4 = c("0", "0", "0", "0", "0"), 
      week5 = c("0", "0", "0", "0", "0"), week6 = c("0", "0", "0", "0", "0"), 
      week7 = c("0", "0", "0", "0", "0"), week8 = c("0", "0", "0", "0", "1")), 
      row.names = c(NA, 5L), class = "data.frame")) 

 for(i in 1:length(out)){
  n = paste(paste(names(out)[i],Sys.Date(), sep = "_"),  ".csv", sep = "")  # create set name and version control
  write.csv(out[i], file = n, row.names = FALSE, col.names = c("week4", "week5", "week6", "week7", "week8"))
}

Sorry for the lack of decent tags... I don't have the reputation to set tags that I think are useful for this post and couldn't find ones that made sense in the ones available.

Upvotes: 1

Views: 1353

Answers (1)

akrun
akrun

Reputation: 887118

We don't need to specify the col.names. The issue seems to be that, the list elements are not extracted correctly. It should be [[i]] instead of [i]. With [i], it is still a list of one data.frame element. By doing [[i]], it extracts the data.frame from the list

for(i in seq_along(out)){
   n <- paste(paste(names(out)[i],Sys.Date(), sep = "_"),  
                     ".csv", sep = "")  
    write.csv(out[[i]], file = n, row.names = FALSE, quote = FALSE)
   }

The difference can be found from checking the str

str(out[[1]])
str(out[1])    

Upvotes: 3

Related Questions