问题
I have this code:
library(jsonlite)
df <- fromJSON('blarg.json')
from this json (in a file called blarg.json
):
[{ "id": 211,
"sub_question_skus": { "0": 329, "behavior": 216 } },
{ "id": 333,
"sub_question_skus": [ 340, 341 ] },
{ "id": 345,
"sub_question_skus": [ 346, 352 ] },
{ "id": 444,
"sub_question_skus": null }]
That produces a data frame like so:
> df
id sub_question_skus
1 211 329, 216
2 333 340, 341
3 345 346, 352
4 444 NULL
Ah, but look, its structure is quite complicated in the RStudio viewer:
I want something like:
df_expanded <- data.frame(id=c(211, 211, 333, 333, 345, 345),
sub_question_sku=c(329,216,340,341,346,352))
> df_expanded
id sub_question_sku
1 211 329
2 211 216
3 333 340
4 333 341
5 345 346
6 345 352
How do I get that?
For context, I'm trying to update rsurveygizmo to handle sub-questions from Survey Gizmo. It's uphill going for me.
回答1:
Hacky, but a start:
df$sub_question_skus <- replace(
df$sub_question_skus,
sapply(df$sub_question_skus, is.null), NA)
as.data.frame(
do.call(
rbind,
Map(f=cbind, id=df$id, sub=df$sub_question_skus)),
row.names = FALSE)
# id sub
# 1 211 329
# 2 211 216
# 3 333 340
# 4 333 341
# 5 345 346
# 6 345 352
# 7 444 NA
来源:https://stackoverflow.com/questions/60962626/how-to-unpack-this-jsonlite-return-value-in-r