2015-05-06 34 views
0

我從mongodb集合創建了一個數據表。在此數據表中的數據是JSON格式,但我不能讓從中提取信息..從數據集(json格式)獲取信息r

{「地方」:{「bounding_box」:{ 「類型」:「多邊形」, 「座標」 : [ [ -119.932568, 36.648905 ], [ -119.632419, 36.648905 ] ] ] }}}

我需要的座標的前兩個值:LAT = 36.648905和經度= -119.932568

,但不能似乎提取信息:

my_lon <- myBigDF$place.bounding_box.coordinates[1[1[1]]] 

我已經試過幾個組合,但我總是獲得NULL。 謝謝你的任何幫助..

- 編輯 - 包括對我如何連接到數據庫,並創建從它的數據幀代碼..

mongo <- mongo.create(host="localhost" , db="mydb") 

library(plyr) 
## create the empty data frame 
myDF = data.frame(stringsAsFactors = FALSE) 

## create the cursor we will iterate over, basically a select * in SQL 
cursor = mongo.find(mongo, namespace) 
## create the counter 
i = 1 

## iterate over the cursor 
while (mongo.cursor.next(cursor)) { 
    # iterate and grab the next record 
    tmp = mongo.bson.to.list(mongo.cursor.value(cursor)) 
    # make it a dataframe 
    tmp.df = as.data.frame(t(unlist(tmp)), stringsAsFactors = F) 
    # bind to the master dataframe 
    myDF = rbind.fill(myDF, tmp.df) 
} 

回答

0

很難確切地告訴你如何從JSON字符串轉到R對象。有不同的庫以不同的方式解析事物。如果我假設了一下使用「rjson」,那麼你就必須像

x <- rjson::fromJSON('{"place":{"bounding_box":{ "type":"Polygon", "coordinates":[ [ [ -119.932568, 36.648905 ], [ -119.632419, 36.648905 ] ] ] }}}') 

而且因爲你的數據似乎有方括號的數量過多,事情有點亂。你可以到達座標部分

x$place$bounding_box$coordinates 
# [1]] 
# [[1]][[1]] 
# [1] -119.9326 36.6489 
# 
# [[1]][[2]] 
# [1] -119.6324 36.6489 

這是一個向量列表列表。爲了使LAT一個很好的矩陣/經度座標,你可以做

do.call(rbind, x$place$bounding_box$coordinates[[1]]) 
+0

@MrFlink謝謝,我也嘗試這種方法,但我仍然得到NULL - 我已經編輯職位,其中包括有關我如何創建代碼數據幀。再次感謝.. – user3784080

+0

代碼沒有幫助,因爲我們無法運行它,所以我們不知道它返回的是什麼。此時,您似乎並沒有與JSON進行交互,因爲這主要是您描述數據的方式。我想你會需要分享'dput(myDF)'來了解你真的在處理什麼類型的數據結構。 – MrFlick

+0

dput(myDF)給了我class =「data.frame」,但是當我做my_lon < - myBigDF $ place.bounding_box.type時它工作並返回Polygon。此外,嘗試x < - rjson :: fromJSON(myDF),但得到一個錯誤「無法轉義字符串。字符串不是utf8」。謝謝 – user3784080