从R数据框的行中提取JSON数据 [英] Extract JSON data from the rows of an R data frame

查看:416
本文介绍了从R数据框的行中提取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中 Parameters 列的值为Json数据:

I have a data frame where the values of column Parameters are Json data:

#  Parameters
#1 {"a":0,"b":[10.2,11.5,22.1]}
#2 {"a":3,"b":[4.0,6.2,-3.3]}
...

我想提取每一行的参数并将它们作为列 A B1 B2 B3 .

I want to extract the parameters of each row and append them to the data frame as columns A, B1, B2 and B3.

我该怎么办?

如果可能且高效,我宁愿使用 dplyr .

I would rather use dplyr if it is possible and efficient.

推荐答案

在您的示例数据中,每一行都包含一个json对象.这种格式称为 jsonlines aka ndjson ,而jsonlite包具有特殊功能stream_in,可将此类数据解析为数据帧:

In your example data, each row contains a json object. This format is called jsonlines aka ndjson, and the jsonlite package has a special function stream_in to parse such data into a data frame:

# Example data
mydata <- data.frame(parameters = c(
  '{"a":0,"b":[10.2,11.5,22.1]}',
  '{"a":3,"b":[4.0,6.2,-3.3]}'
), stringsAsFactors = FALSE)

# Parse json lines
res <- jsonlite::stream_in(textConnection(mydata$parameters))

# Extract columns
a <- res$a
b1 <- sapply(res$b, "[", 1)
b2 <- sapply(res$b, "[", 2)
b3 <- sapply(res$b, "[", 3)

在您的示例中,json结构非常简单,因此其他建议也可以使用,但是此解决方案将推广到更复杂的json结构.

In your example, the json structure is fairly simple so the other suggestions work as well, but this solution will generalize to more complex json structures.

这篇关于从R数据框的行中提取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆