koteletje
koteletje

Reputation: 679

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 productSales as a txt 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 write.table.

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

Upvotes: 0

Views: 56

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545638

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).

Upvotes: 2

Related Questions