Thomas Lee
Thomas Lee

Reputation: 383

How to output a list to file in R

Assume having a list of books with authors , after reading the data into a list "LS" I tried to enter it into a file and the output was

> write.table(LS, "output.txt")
Error in data.frame(..., title = NULL,  : 
  arguments imply differing number of rows: 1, 0

> write(LS, "output.txt")
Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

I was able to use dput but I would like the data to be formatted well (no redundancy of repeated keywords all over the file). Any suggestions? Thanks

UPDATE dput( head (LS, 2))

list(structure(list( title = "Book 1", 
authors = list(structure(c("Pooja", "Garg"),
 .Names = c("forename","surname")), 
structure(c("Renu", "Rastogi"), 
.Names = c("forename","surname")))),
 .Names = c("title", "authors")), 

structure(list( title = "Book 2", 
 authors = list(structure(c("Barry", "Smit"), .Names = c("forename", 
    "surname")), structure(c("Tom", "Johnston"), .Names = c("forename", 
    "surname")))), .Names = c("title", "authors")))

Upvotes: 11

Views: 38604

Answers (4)

Shahryar
Shahryar

Reputation: 1474

It's better to use format()

LS.str <- format(LS)

Upvotes: 0

remykarem
remykarem

Reputation: 2469

I use the RJSONIO package.

library(RJSONIO)

exportJSON <- toJSON(LS)
write(exportJSON,"LS.json")

Upvotes: 2

mnel
mnel

Reputation: 115382

Using the data you provided and rjson

library(rjson)

# write them to a file
cat(toJSON(LS), file = 'LS.json')


LS2 <- fromJSON('LS.json')


# some rearranging to get authors back to being a data.frame

LS3 <- lapply(LS2, function(x) { x[['authors']] <-  lapply(x[['authors']], unlist); x})

identical(LS, LS3)

## TRUE

The file looks like

[{"title":"Book 1","authors":[{"forename":"Pooja","surname":"Garg"},{"forename":"Renu","surname":"Rastogi"}]},{"title":"Book 2","authors":[{"forename":"Barry","surname":"Smit"},{"forename":"Tom","surname":"Johnston"}]}]

if you want each book on a separate line then you can use

.json <-  lapply(LS, toJSON)
# add new lines and braces

.json2 <- paste0('[\n', paste0(.json, collapse = ', \n'), '\n]')
 cat(.json)
[
{"title":"Book 1","authors":[{"forename":"Pooja","surname":"Garg"},{"forename":"Renu","surname":"Rastogi"}]}, 
{"title":"Book 2","authors":[{"forename":"Barry","surname":"Smit"},{"forename":"Tom","surname":"Johnston"}]}
]

Upvotes: 9

Ali
Ali

Reputation: 9830

You may first convert your list to a data frame:

LS.df = as.data.frame(do.call(rbind, LS))

Or

LS.df = as.data.frame(do.call(cbind, LS))

Then you can simply save LS.df with write.csv or write.table

Upvotes: 10

Related Questions