json - Building a data frame row by row from a list -



json - Building a data frame row by row from a list -

i parsing info construction looks in r:

[ { 'firstname': 'abc', 'lastname' : 'def' }, { 'firstname': 'abc2', 'lastname' : 'def2' } ]

i want store info in info frame. current approach flawed , feels messy. have several info sets, need specify columns. can suggest 'cleaner'?

problem 1: need specify info names

library(rjson) listdata <- fromjson(jsondata) listnames <- c('firstname', 'lastname') (player in listdata){ playercols = c() (name in listnames){ value <- player[[name]] if (is.null(value}{value <- "na"} playercols <- c(playercols, value) } # code convert playercols data.frame goes here. }

i run extraction if possible without using column names, or in such way extract columns info go along. tricky part here not columns populated in each entry. i'd final info frame know columns , set missing values na

problem 2: seem fail adding row of data, instead lists created columns

for (player in listdata){ # code extract columns here df = data.frame(playercols, name=listnames) print(df) }

instead of creating 2 column info frame rows contain info , names, want single row, named columns, can rbind together.

it's bad thought seek build data.frame row-by-row. it's not efficient process. it's improve build info column column , combine data.frame @ end. first, let's utilize sample info has missing values describe

a<-'[ { "firstname": "abc", "lastname" : "def" }, { "firstname": "abc2" } ]'

let's build helper function extract value list if exists, or homecoming na if not

extr<-function(list,ele) { x<-list[[ele]] if (is.null(x)) x=na; x }

if want grab values without having specify tag names explicitly, can find them using

listnames <- unique(unlist(lapply(listdata, names)))

now can convert json list, , extract vector of column values each time , combine them data.frame with

listdata <- fromjson(a) data.frame(map(function(n) sapply(listdata, extr, n), listnames))

here utilize map rather more customary lapply because utilize values of listnames names returned list.

json r data.frame

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -