r - 从R中的字符串中提取特定关键字

标签 r pattern-matching text-extraction

我的表中有一个“地点”列,其中包含有关某个地点的数据,如下所示:

{ "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 是包含我的整个表的数据框。目前,我只对表中的地点字段感兴趣,其中包含上述格式的信息。因此,我尝试使用基本赋值指令将地点字段加载到名为“loc”的单独变量中:

loc <- t1$place

为了将其作为 JSON 读取,地点字段需要用单引号分隔,但它最初并非如此。我的表中有 200 万行,所以我真的无法手动添加分隔符。

最佳答案

这看起来像一个 JSON 对象,因此使用 JSON 解析来提取数据会更容易。

如果这是你的字符串值

x <- '{ "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" }'

那么你可以这样做

library(jsonlite)
# or library(RJSOINIO)
# or library(rjson)

fromJSON(x)$country
# [1] "United States"

关于r - 从R中的字符串中提取特定关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268906/

相关文章:

r - 如果数据行在指定时间段内具有顺序时间间隔,则合并数据行

r - 使用 dplyr 在行和列表上映射一个简单的计算

reshape 世界银行数据格式

algorithm - 将曲线图案与图像的边缘相匹配

f# - 避免 "Incomplete pattern match"警告的替代方法

pdf - 如何从 PDF 中提取文本?

r - 使用 ggplot2 如何表示图例中的点和线

algorithm - 稳定匹配问题

php - 在第一个连字符之前隔离字符串的前导部分,并从匹配中省略任何尾随空格

r - 从字符串中提取状态缩写和邮政编码