lapply(names(df),function(x){ tb <- table(df[[x]]);
write.table(file="test.csv", append=TRUE, quote=FALSE,
row.names=FALSE, col.names=FALSE, sep=";",
x= paste(x, paste( names(tb), tb, collapse=";", sep=";") ,
sep=";")
)})
#--------
fruit;Apple;2;Pear;1
veg;Carrot;1;Peas;1;Potato;1
meat;Chicken;1;Duck;1;Steak;1
You will also see a list of three NULLs which would not be sent to a text file. Writing tables and matrices to files is not a strong point of R. There is a write.matrix
function in package::MASS. My initial effort with writeLines
failed because it has no 'append' option and I wasn't able to cobble together a connection call that would do the append
.
(The other gotcha' in R is that processing a list (and by inheritance a dataframe) with 'apply/lapply/sapply' does not pass the names
of the list-element (and colnames
for dataframes) to the function, so "write" functions would not have the names internally for writing to a file. That is why I worked with names(df)
rather than just df
.
As a further note, there are probably JSON-writing functions out there and they might be more reliable. I'll take a look and report back.
There is the RJSONIO package:
> require(RJSONIO)
Loading required package: RJSONIO
> toJSON(df)
[1] "{\n \"fruit\": [ \"Apple\", \"Apple\", \"Pear\" ],\n\"veg\": [ \"Carrot\", \"Potato\", \"Peas\" ],\n\"meat\": [ \"Steak\", \"Chicken\", \"Duck\" ] \n}"