简体   繁体   中英

How to convert a list with same type of field to a data.frame in R

I have a list and the field inside each list element is of same name(only values are different) and I need to convert that into a data.frame with column name is same as that of field name. Following is my list,

Data input (data input in json format.json)

library(rjson)
data <- fromJSON(file = "data input in json format.json")
head(data,3)
[[1]]
[[1]]$floors
[1] 5

[[1]]$elevation
[1] 15

[[1]]$bmi
[1] 23.7483


[[2]]
[[2]]$floors
[1] 4

[[2]]$elevation
[1] 12

[[2]]$bmi
[1] 23.764


[[3]]
[[3]]$floors
[1] 3

[[3]]$elevation
[1] 9

[[3]]$bmi
[1] 23.7797

And my expected data.frame is,

floors elevation     bmi
     5        15 23.7483
     4        12 23.7640
     3         9 23.7797

Can you help me to figure out this ?. Thanks in adavance.

You can use jsonlite .

library(jsonlite)

Then use fromJSON() and specify the path to your file (or alternatively a URL or the raw text) in the argument txt :

fromJSON(txt = 'path/to/json/file.json')

The result is:

     floors elevation     bmi
1         5        15 23.7483
2         4        12 23.7640
3         3         9 23.7797

If you prefer rjson, you could first read it as previously:

data <- rjson::fromJSON(file = 'path/to/json/file.json')

Then use do.call() and rbind.data.frame() to convert the list to a dataframe:

do.call("rbind.data.frame", data)

Alternatively to do.call() : use data.table s rbindlist() which is faster:

data.table::rbindlist(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM