我正在寻找上述的简单解决方案。当API返回JSON(随后将其转换为列表)时,我似乎经常遇到此问题。
代表数据:
result_head <- list(list(name = "JEFFREY", gender = "male", probability = 1L,
count = 932L), list(name = "Jan", gender = "male", probability = 0.6,
count = 1663L), list(name = "Elquis", gender = NULL), list(
name = "ELQUIS", gender = NULL), list(name = "Francisco",
gender = "male", probability = 1L, count = 1513L))
任务是尽可能简单地将其转换为5行数据帧。鉴于每个列表元素中的项目都是不规则的,将需要为丢失的项目引入NA
,类似于bind_rows
的工作原理,即堆叠具有不规则列的数据帧时的工作方式。
我尝试过的事情:
map_dfr(result, bind_rows)
do.call(bind_rows, result_head)
flatten(result_head)
bind_rows(flatten(result_head))
我在这里问了类似的问题: Extracting to a data frame from a JSON generated multi-level list with occasional missing elements
...但是该解决方案的设计过于复杂,以简化列表。
我希望有一个尽可能优雅的解决方案-我经常遇到这种操作,但似乎并没有统一的方法来实现很少的功能抽象级别。
我意识到围绕此问题可能已经问过,可能错过了一些东西,但是似乎并没有统一而简单的方法来解决似乎是常见的问题。
谢谢。
答案 0 :(得分:3)
这里是map
转换为flatten
后的tibble
的另一种选择
library(tidyverse)
map_df(result_head, ~ flatten(.x) %>%
as_tibble)
# A tibble: 5 x 4
# name gender probability count
# <chr> <chr> <dbl> <int>
#1 JEFFREY male 1 932
#2 Jan male 0.6 1663
#3 Elquis <NA> NA NA
#4 ELQUIS <NA> NA NA
#5 Francisco male 1 1513
或者就像评论中提到的@ G.Groethendieck
map_dfr(result_head, flatten)
答案 1 :(得分:2)
library(purrr) # transpose and map_if
library(rlist) # list.stack
result_head <- list(
list(name = "JEFFREY", gender = "male", probability = 1L, count = 932L),
list(name = "Jan", gender = "male", probability = 0.6, count = 1663L),
list(name = "Elquis", gender = NULL),
list(name = "ELQUIS", gender = NULL),
list(name = "Francisco", gender = "male", probability = 1L, count = 1513L)
)
list.stack(transpose(
lapply(transpose(result_head), function(y) map_if(y, is.null, function(x) NA))
))
name gender probability count
1 JEFFREY male 1.0 932
2 Jan male 0.6 1663
3 Elquis <NA> NA NA
4 ELQUIS <NA> NA NA
5 Francisco male 1.0 1513