我希望有人可以帮助我解决我遇到的问题。我有列表格式的json
响应。
结构是一个列表。每个列表中都有一个列播放器。它像这样嵌套在每个列表中
df[[1]]$body$wildcards$players
players
列是每个列表中的嵌套df
。如何绑定嵌套在df
中的完整列表的玩家列?
下面的屏幕截图代表。
sample <- list(
list(
body = list(
wildcards = list(
players = data.frame(
firstname = c("Fernando", "Jon"),
throws = c("L", "R")
)
),
statusMessage = "OK",
statusCode = 200
)
),
list(
body = list(
wildcards = list(
players = data.frame(
firstname = c("Eduardo", "James"),
throws = c("L", "R")
)
),
statusMessage = "OK",
statusCode = 200
)
)
)
输出df
tibble::tribble(
~firstname, ~throws,
"Fernando", "L",
"Jon", "R",
"Eduardo", "L",
"James", "R"
)
我们可以将pluck
和map
一起使用
library(purrr)
map_dfr(sample, ~ pluck(.x, 'body', 'wildcards','players'))
# firstname throws
#1 Fernando L
#2 Jon R
#3 Eduardo L
#4 James R
假设每个数据框中的列名相同:
library(data.table)
new_df <- rbindlist(lapply(df,function(x)x$body$wildcards$players),use.names=T,fill=T)
请注意,每个df中的列数不相同,因此,使用fill=T
参数,数据框中将有NA
个。
这能解决您的问题吗?