koteletje koteletje - 1 year ago 98
R Question

Save data frame containing a list column as a " delimited txt file

I have a data frame of which one column is a list; e.g.

x = c("Benny", "Johnny")
y1 = c("Product 1","Product 3","Product 4")
y2 = c("Product 1","Product 2")
myList = vector("list", 2)
myList[[1]] = y1
myList[[2]] = y2

productSales = data.frame(x, cbind(myList), stringsAsFactors = FALSE)
colnames(productSales) = c("Name", "Product")

I succeed to save
as a
file through

capture.output(twoDifferentPfFlags, file = "result.txt")

My problem with this method, however, is that columns are not delimited with
as one would get using

Is there a way to generate
delimited results table when a column of a data frame contains a list?

Answer Source

I’m not aware of a builtin way of saving list columns. In your particular case, you could convert the list column to a character column by pasting the values:

productSales$Product = unlist(lapply(productSales$Product, paste, collapse = ', '))

Afterwards, you can use write.table (or a more modern equivalent such as readr::write_csv).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download