【问题标题】:Unnest json file with coordinates into dataframe in R将带有坐标的json文件嵌套到R中的数据框中
【发布时间】:2017-10-19 13:30:22
【问题描述】:

我在将 json 文件解析为 R 中的数据框时遇到问题。我已经能够将 json 文件转换为数据框,但我似乎无法取消嵌套“几何”列。下面是一个json文件的示例

[
{
    "point_id": 4,
    "geometry": {
        "type": "Point",
        "coordinates": [
            -101.5961904,
            31.7070736
        ]
    },
    "NumericID": "4543842",
}
]

当我尝试使用下面的代码取消嵌套时,出现错误。

ex_data<-lapply(ex_data, function(x) ifelse (x == "NULL", NA, x))
ex_data<-as.data.frame(do.call(rbind, ex_data))
ex_data<-ex_data%>% bind_rows(ex_data) %>%    # make larger sample data
mutate_if(is.list, simplify_all)   # flatten each list element internally 
ex_data%>%unnest(geometry)->ex_data_unnest
Error: Each column must either be a list of vectors or a list of data frames 
[geometry]

谢谢

【问题讨论】:

    标签: json r coordinates unnest


    【解决方案1】:

    使用jsonlite::stream_in() 读取 JSON 文件(我在 JSON 文件中复制了您的示例多次):

    df <- stream_in(file("test.json"))
    

    编辑:

    取消嵌套几何列:

    df <- as.data.frame(cbind(df[,-2],
        do.call(rbind,df$geometry$coordinates),     
        df$geometry$type),
        stringsAsFactors = F)
    names(df)[3:5] <- c("geometry.coordinates1","geometry.coordinates2","geometry.type")
    
    df
       point_id NumericID geometry.coordinates1 geometry.coordinates2 geometry.type
    1         4   4543842             -101.5962              31.70707         Point
    2         4   4543842             -101.5962              31.70707         Point
    

    现在您可以访问来自data.frame 的值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2015-09-24
      • 2017-02-28
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多