【发布时间】:2019-07-03 13:42:02
【问题描述】:
作为我论文的一部分,我正在分析政党的极性。在接收到 JSON 格式的 Facebook 消息的数据转储后,我将其解析为 R。不幸的是,嵌套了一个列表变量:
我需要从列表中列表中的列表中提取$sentiment$polarity$score。
Observations: 63,465
Variables: 5
$ description <chr> "'TEXT'" ...
$ parties <list> ["X", "X", "Y", ...
$ date <date> 2018-03-05, 2018-03-05...
$ title <chr> NA, NA...
$ sentiment <list> [[[0.2998967, "Positief"], ...
使用glimpse(df$sentiment) 显示:
$ :List of 2
..$ polarity :List of 2
.. ..$ score : num 0.15
.. ..$ description: chr "Neutraal"
..$ subjectivity:List of 2
.. ..$ score : num 0.65
.. ..$ description: chr "Erg subjectief"
[list output truncated]
编辑:head(df$sentiment, n=1) 给出:
[[1]]
[[1]]$`polarity`
[[1]]$`polarity`$`score`
[1] 0.2998967
[[1]]$`polarity`$description
[1] "Positief"
[[1]]$subjectivity
[[1]]$subjectivity$`score`
[1] 0.5458678
[[1]]$subjectivity$description
[1] "Subjectief"
但是,df$sentiment 的问题部分存在于(运行head(df$sentiment, n=10) 时)如下:
[[5]]
named list()
因此,观察确实包含一个空列表,而不是包含其他两个列表的格式。
我尝试了以下方法:
df %>% unnest(sentiment, .drop = FALSE, .sep = '"')
不幸的是,这使我的 df 翻了一番,从而失去了 polarity$score 和 sentiment$score 之间的区别。
我也试过了
matrix(unlist(df$sentiment),ncol=4,byrow=TRUE)
不幸的是,这无法处理 NULL 条目(即当$sentiment 为空而$polarity 不为空时)。因此,它创建了一个有缺陷的矩阵。
我也玩过flatten、unlist 和tranpose 函数,但这似乎并没有让我有任何收获。我在 R 方面没有那么有经验,因此我希望有人可以帮助我提取正确的分数并将其作为列输入到我的数据框中。我希望我提供了所有需要的信息。
【问题讨论】:
-
您能否提供更长的
sentiment示例。每个sentiment$polarity$score的长度都是两个吗?您的代码matrix(unlist(df$sentiment), ncol = 4, byrow = TRUE)似乎是一个好的开始,也许可以尝试创建一个if(length(df$sentiment) == 0){ rep(NA, 4)}。这可以捕获NULL的条目并用NA填充它,因此不会产生错误。 -
(1)
sentiment$polarity$score的每个观察值都包含一个介于 +1 和 -1 之间的数值。 (2) 上面的帖子中提供了通过head(df$sentiment)的更长的情感示例。 (3) 我会在一分钟内运行你的尝试和更新!感谢您的建议。 -
我试过你的建议@Rex,谢谢!不幸的是,这不起作用(因为条目不是“NULL”,而只是一个空列表)。我可以尝试使用
flatten,但这放弃了$polarity$score和$sentiment$score之间的区别。
标签: r