【问题标题】:How to join nested values into one column with tidyjson?如何使用 tidyjson 将嵌套值加入一列?
【发布时间】:2016-09-22 13:39:32
【问题描述】:

我想在一列中加入两个值而不是展开

'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
spread_values(
first.name = jstring("name", "first"), 
age = jnumber("age")
) %>%
unite(conc, c("first.name", "age"), sep=" ")

但我一直有以下错误

所有 select() 输入必须解析为整数列位置。 以下不: c("first.name", "age")

我希望的输出是有一个新列“conc”替换 first.name 和 age 并连接每个字符串值。比如“琼斯 32”

这很奇怪,因为如果我删除最后一行,它会给我一个正确的 data.frame,我可以访问 first.name 和 age。

有什么提示吗?

【问题讨论】:

  • 期望的输出是什么?
  • '{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>% jsonlite::fromJSON() %>% as.data.frame() 没问题。

标签: json r dataframe tidyr


【解决方案1】:

虽然tbl_json 对象继承自tbl_df,但一旦您完成解析并开始在tidyjsondplyr 中进行进一步操作,它们有时就不能很好地发挥作用。原因是你有额外的方法和属性标记,这些已经不再需要了。

因此,一旦完成解析,使用tbl_dfas_data_frame 剥离对象的tbl_json 组件是一个好习惯。我更喜欢tbl_df,因为它更短。

我使用的是来自github的开发版:devtools::install_github('jeremystan/tidyjson')

我无法重现您提到的错误,但这似乎有效:

library(tidyjson)
library(tidyr)

"{\"name\": {\"first\": \"bob\", \"last\": \"jones\"}, \"age\": 32}" %>% 
spread_values(first.name = jstring("name","first")
  , age = jnumber("age")
) %>% 
tbl_df() %>% 
unite(conc, c("first.name", "age"), sep = " ")

#> # A tibble: 1 x 2
#>   document.id   conc
#> *       <int>  <chr>
#> 1           1 bob 32

在连接字符串时,其他值得深思的是在mutate 中使用paste()paste0()mutate 也受tidyjson 支持,因此可以在解析JSON 时在管道中使用它。在使用 summarize 聚合多行时,paste(.,collapse=',') 也非常有用。

【讨论】:

    【解决方案2】:
    library(jsonlite)
    json <- lapply( paste0("[",'{"name": {"first": "bob", "last": "jones"}, "age": 32}',"]"), 
                    function(x) jsonlite::fromJSON(x))
    ##json is a list
    
    df <- data.frame(matrix(unlist(json), nrow=1, ncol=3, byrow=T))
    
    df <- df %>% unite(Name, X1, X3, sep = " ")
    df <- subset(df, select=-X2)
    colnames(df) <- c("conc")
    df
    

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 2019-11-01
      • 2023-03-20
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多