[英]Unnest json file with coordinates into dataframe in R
我在將json文件解析為R中的數據框時遇到了麻煩。我已經能夠將json文件轉換為數據框,但是我似乎並沒有打擾“ geometry”列。 以下是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]
謝謝
使用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
的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.