【问题标题】:Extract a specific key word from a string in R从R中的字符串中提取特定关键字
【发布时间】: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


    【解决方案1】:

    这看起来像一个 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"
    

    【讨论】:

    • 感谢您的及时回复。请原谅我的无知,但字段位置在字符串的开头和结尾没有单引号。因此,当我尝试以下操作时,它会显示错误: x
    • 我认为fromJSON(t1$place) 会起作用。您确实没有提供足够的详细信息来制作数据reproducible(请参阅该链接以获取提示)。
    • codeloc
    • fromJSON(as.character(t1$place)) 怎么样(同样,如果您提供一个可重现的示例会更容易,因为此时我只能根据错误消息进行猜测)。
    • 哇,这行得通,但只解析了第一行。我应该为表的所有行编写一个循环吗?另外,我编辑了这个问题。请让我知道这是否足够。很抱歉信息不完整。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多