2016-09-06 3 views
2

동일한 구조의 JSON 벡터를 가지고 data.frame으로 변환합니다. 다음 예제는 내가 원하는 것을 정확하게 수행합니다. 나는 그것을 fromJSON()를 변환하면 JSON의R : data.frame에 대한 JSON 벡터

require(jsonlite) # fromJSON() 
require(magrittr) # for the pipeline only 
require(data.table) # rbindlist() 

jsons <- c('{"num":1,"char":"a","list":{"x":1,"y":2}}', 
      '{"num":2,"char":"b","list":{"x":1,"y":2}}', 
      '{"num":3,"char":"c","list":{"x":1,"y":2}}') 

df <- jsons %>% 
    lapply(fromJSON) %>% 
    lapply(as.data.frame.list, stringsAsFactors = F) %>% 
    rbindlist(fill = T) 

일부 요소 목록의 일부 요소뿐만 아니라 목록 될 것, 즉 개체입니다. 내가 다른 변수 유형을 가지고 있기 때문에 나는 as.data.frame.list() 함수를 사용하기 때문에 각 목록에 unlist()을 사용할 수 없다. 그러나 각 JSON에 대해 개별적으로 수행하는 것은 너무 느립니다. 어떻게하면 더 효과적으로 할 수 있을까요?

json <- '{"$schema":"http://json-schema.org/draft-04/schema#","title":"Product set","type":"array","items":{"title":"Product","type":"object","properties":{"id":{"description":"The unique identifier for a product","type":"number"},"name":{"type":"string"},"price":{"type":"number","minimum":0,"exclusiveMinimum":true},"tags":{"type":"array","items":{"type":"string"},"minItems":1,"uniqueItems":true},"dimensions":{"type":"object","properties":{"length":{"type":"number"},"width":{"type":"number"},"height":{"type":"number"}},"required":["length","width","height"]},"warehouseLocation":{"description":"Coordinates of the warehouse with the product","$ref":"http://json-schema.org/geo"}},"required":["id","name","price"]}}' 
system.time(
    df <- json %>% rep(1000) %>% 
    lapply(fromJSON) %>% 
    lapply(as.data.frame.list, stringsAsFactors = F) %>% 
    rbindlist(fill = T) 
) # 2.72 

나는 비슷한 질문이 많이 있다는 것을 알고 있지만 내가 본 답변의 대부분은 as.data.frame() 또는 data.frame() 사용에 대한했다. 아무도 속도를 언급하지 않았다. 아마 이것에 대한 더 좋은 해결책은 없을 것입니다.

답변

1

나는 결국 answer을 발견했다. CRAN soon에 있습니다.

devtools::install_github("jeremystan/tidyjson") 
tidyjson::spread_all() 

이 기능은 위의 예보다 약 10 배 빠릅니다.