1

I'm writing to disk a bunch of data frames using write.csv:

data_frames <- Filter(function(x) is(x, "data.frame"), mget(ls()))

for (i in 1:length(data_frames)) {

 file_name<- paste0("data/to_save/",names(data_frames[i]),".csv")

 write.csv(data_frames[i], file = file_name, row.names = FALSE, col.names = TRUE)

} 

The issue is that header is messed adding filename to every colname like this (opened a file with notepad):

"April2016_file.customer_id","April2016_file.customerName","April2016_file.customerSurname".......

Same behaviour using write.tableand using export script from package rio

Required result:

"customer_id","customerName","customerSurname"....
Forge
  • 1,587
  • 1
  • 15
  • 36
  • 1
    For more information either look at the documentation (`?"["`) or see http://stackoverflow.com/questions/1169456/ – talat Feb 15 '17 at 12:11

1 Answers1

1

We need to extract the list elements with [[ as [ is still a list with a single data.frame

for (i in seq_along(data_frames)) {
  file_name<- paste0("data/to_save/",names(data_frames[i]),".csv")
   write.csv(data_frames[[i]], file = file_name, row.names = FALSE, col.names = TRUE)
} 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    No completely understood behaviour, but akrun suggestion did the trick. Thanks!!! – Forge Feb 15 '17 at 12:12
  • @Forge What happens is when you are a writing a list element, it also has a name which gets appended, while with `[[`, you are extracting the `list` element, so you are avoidng it. i.e. `lst <- setNames(1:3, LETTERS[1:3]); lst[1]` vs `lst[[1]]` – akrun Feb 15 '17 at 12:15
  • akrun, in this case I think you could have closed the question with the link I provided since the question shows that OP only requires the correct understanding of the difference between the two extraction functions (which is well explained in the linked Q).. but I didn't since you already answered with a working solution. – talat Feb 15 '17 at 12:26
  • @docendodiscimus I posted the solution before you commented.. I guess this is in reply to my Possible dupe tag in other post. – akrun Feb 15 '17 at 12:37