【发布时间】:2015-05-15 21:19:35
【问题描述】:
我的表中有一个“地点”列,其中包含有关某个地点的数据,如下所示:
{ "id" : "94965b2c45386f87", "name" : "New York", "boundingBoxCoordinates" : [ [ { "longitude" : -79.76259, "latitude" : 40.477383 }, { "longitude" : -79.76259, "latitude" : 45.015851 }, { "longitude" : -71.777492, "latitude" : 45.015851 }, { "longitude" : -71.777492, "latitude" : 40.477383 } ] ], "countryCode" : "US", "fullName" : "New York, USA", "boundingBoxType" : "Polygon", "URL" : "https://api.twitter.com/1.1/geo/id/94965b2c45386f87.json", "accessLevel" : 0, "placeType" : "admin", "country" : "United States" }
从中,我想提取国家名称。我试过以下代码:
loc <- t1$place
loc = gsub('"', '', loc)
loc = gsub(',', '', loc)
清理字符串,现在看起来像这样:
"{ id : 00ed6f0947c230f4 name : Caloocan City boundingBoxCoordinates : [ [ { longitude : 120.9607709 latitude : 14.6344661 } { longitude : 120.9607709 latitude : 14.7873208 } { longitude : 121.1015117 latitude : 14.7873208 } { longitude : 121.1015117 latitude : 14.6344661 } ] ] countryCode : PH fullName : Caloocan City National Capital Region boundingBoxType : Polygon URL : https://api.twitter.com/1.1/geo/id/00ed6f0947c230f4.json accessLevel : 0 placeType : city country : Republika ng Pilipinas }"
现在要提取国家名称,我想使用 word() 函数:
word(loc, n, sep=fixed(" : "))
其中n在国名的位置我还是没算。但是这个函数在 n=1 时给出了正确的输出,但是对于 n 的任何其他值都会给出错误:
Error in word[loc, "start"] : subscript out of bounds
为什么会这样? loc 变量肯定有更多的单词。或者有人可以建议从该字段中提取国家名称的更好方法吗?
编辑:t1 是组成我整个表的数据框。目前我只对包含上述格式信息的表格的位置字段感兴趣。因此,我尝试使用基本赋值指令将 place 字段加载到一个名为“loc”的单独变量中:
loc <- t1$place
为了将其作为 JSON 读取,place 字段需要用单引号分隔,而它原本不是。我的表中有 200 万行,所以我真的无法手动添加分隔符。
【问题讨论】:
标签: r pattern-matching text-extraction