1

I want to import some data which is all in one line and looks like this:

{"name":["Harry"], "eyes":["blue"], "hair":["black"]},{"name":["Sally"], "eyes":["green"], "hair":["brown"]},{"name":["Charlie"], "eyes":["brown"], "hair":["none"]}

Rows are delimited by {} and column names are in " ", so I would want it to look like this:

name    eyes   hair
Harry   blue   black
Sally   green  brown
Charlie brown  none

I'm very new to R. So, I've tried to use read.table using "," as a separator.

df <- read.table(dataPath, header = FALSE, sep=",")

Of course, this only separates the columns, so it doesn't solve my problem because I get a lot of columns and only one row.

I was wondering what was the best way to separate the rows delimited by {} and also if there is a way to get the headers/columns right using R.

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41

1 Answers1

0

Importing data from a JSON file into R suggests an approach which may be suitable. For your string

library("rjson")
vec <- '{"name":["Harry"], "eyes":["blue"], "hair":["black"]},{"name":["Sally"], "eyes":["green"], "hair":["brown"]},{"name":["Charlie"], "eyes":["brown"], "hair":["none"]}'
vec <- fromJSON(paste("[", vec, "]"))
do.call(rbind, lapply(vec, unlist))
     name      eyes    hair   
[1,] "Harry"   "blue"  "black"
[2,] "Sally"   "green" "brown"
[3,] "Charlie" "brown" "none" 
user2957945
  • 2,353
  • 2
  • 21
  • 40