2

I've been storing my data in a structure that looks like this:

dictionary = {'name': 'Jeff', 'state': 'CA', finish_times: [17.34, 12.23]}

When I write it to csv, I only want this data to take up one row, so like:

 Name   State   Finish_Times
'Jeff'  'CA'   [17.34, 12.23]

And I've been able to write the data to a csv exactly like that. The problem is I can't manipulate the list in R. Is there a way to convert the list to a format manageable by R? or will I have to restructure my data?

EDIT: Thanks for all the responses, I've tried using JSON, but I think I'm just gonna manipulate my scraped data within python. That way I can correctly interpret the lists and dictionaries I'm making.

  • are you familiar with pandas? – Espoir Murhabazi Feb 21 '18 at 18:00
  • 1
    There **is no list**. A csv is a series of bytes. There is a valid *python list literal* represented in those bytes, but R doesn't know or care. The *correct* solution would be to use some sort of common serialization format. One option would be to use JSON, popular text-based serialization format. – juanpa.arrivillaga Feb 21 '18 at 18:12
  • According to this answer: https://stackoverflow.com/questions/2061897/parse-json-with-r there are a couple of JSON libraries available for R. The Python standard library comes with the `json` module.I'm not sure *what* sort of R container a JSON object will be deserialized into (Python `dict` objects will be serialized into JSON objects, note, JSON looks a lot like Python literals, indeed, most valid JSON is a valid Python literal (one exception, JSON uses `null` instead of `None`). – juanpa.arrivillaga Feb 21 '18 at 18:16

1 Answers1

1

You can use jsonlite library

you can convert a json format to data frame like this way:

library(jsonlite)
json <-
'[
  {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"}, 
  {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"},
  {},
  {"Name" : "Bowser", "Occupation" : "Koopa"}
]'
mydf <- fromJSON(json)
mydf

this will give you a data frame like this:

   Name   Age  Occupation
1  Mario  32    Plumber
2  Peach  21   Princess
3   <NA>  NA       <NA>
4 Bowser  NA      Koopa

Once you have the data frame you can save it to csv

write.csv(mydf,"myfile.csv",row.names = FALSE)

here is a small tutorial

Víctor Cortés
  • 473
  • 4
  • 9