I have a bunch of .csv files located in the path path
which I import into a list of dataframes named datalist
using the following code:
require(gsubfn) ## to use strapply
datalist <- list()
files <- list.files(path)
for(file in files) {
stem <- gsub("\\.csv$","",file)
datalist[[stem]] <- data.frame(read.delim(file, sep = ";", header=TRUE))
month <- strapply(stem,"^([^_]*).*$")
year <- strapply(stem,"^[^_]*_([^_]*)_.*$")
datalist[[stem]]$Month <- month
datalist[[stem]]$Year <- year
}
(As you may have noticed, I also grab the month and year the data refer to using two regular expressions, but this shouldn't cause the problem I encounter later.)
Then I row-bind all dataframes into a single dataframe named merged
using the rbind
function from the plyr
package:
require(plyr) ## to use rbind
merged <- rbind.fill(datalist)
My problem is that the dataframe I end up with appears to be a strange dataframe of lists: indeed, if I try to export it into a .csv format, R throws me the following error:
write.csv(merged,'merged.csv')
Error in write.table(x, file, nrow(x), p, rnames, sep, eol, na, dec, as.integer(quote),:
unimplemented type 'list' in 'EncodeElement'
And another similar error is thrown at me if I try to reshape the dataframe using the melt
and cast
functions from the reshape
package:
require(reshape) ## to use melt and cast
molten <- melt(merged)
cast <- cast(molten, ...formula...)
Error in order(var1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, :
unimplemented type 'list' in 'listgreater'
So, how can I obtain a normal dataframe from a list of dataframe? I think the problem is in the "importing" process, as the same error unimplemented type 'list' in 'EncodeElement'
is thrown at me even if I try to export to .csv just one single dataframe in the datalist
list.
Thanks a lot.