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")))
In this approach user first need to create the list of any datatype and then need to call capture. output() function with the created list by the user and name of the file into which the user has to export the created list as the parameter of the function.
For example, if we have a list called List and we want to print all the elements of the list then we can use the code for(i in List){print(i)}, here i refers to the vectors in the List.
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
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"}]}]
.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"}]}
]
I use the RJSONIO package.
library(RJSONIO)
exportJSON <- toJSON(LS)
write(exportJSON,"LS.json")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With