【问题标题】:Why does my stringr function fail halfway through my dataset?为什么我的 stringr 函数在我的数据集中途失败?
【发布时间】:2020-04-13 05:33:46
【问题描述】:

我正在尝试从一个小型(约 13,000 obs)医疗保健数据集中的一些字符串中提取日期,以进行文本分析。

名为Current Tracking Events的示例数据字段:

06/12/2019 Day 2: OPA with JK/MD. CT colonoscopy requested. | 17/12/2019 Day 13: CT colonoscopy: 

通常有比这更多的数据由额外的管道分隔 |

我正在使用以下代码:

extracted_data <- 
original data %>% 

  unnest_tokens(comment, `Current Tracking Events`, token = "regex", pattern = "[|]") %>% # to first divide the data by the piped sections

mutate(comment_date = str_detect(comment, pattern = "\\d+/\\d+/\\d+")) # extract the date at the start of the comment

这适用于前约 3,000 次观察,但随后失败并返回 NA。当我提取一些失败的特定观察集时,它会再次起作用。我不知道我可以运行哪些其他测试来理解为什么它没有提取我需要的信息。任何人都可以解释一下吗?我已经通过 Google 和文档进行了搜索,但看不到可能出了什么问题。

数据集已使用 odbc 包从 microsoft sql server 导入到 r。

【问题讨论】:

    标签: r string text


    【解决方案1】:

    尝试将文件作为管道分隔的文件从头开始读取:

    library(readr)
    df <- read_delim("path/to/your/file.psv", delim = "|")
    

    此函数将读取所有正确的行并警告您出现问题。您可以像这样查看哪些行不正确:problems(df)

    【讨论】:

    • 感谢您的回答!我不确定这是否会起作用,因为我从 sql 服务器中提取的数据集中还有许多其他字段没有用“|”分隔。我会继续努力,看看我能不能找到一些有用的东西。我现在尝试从我的字符串中删除所有非 UTF-8 字符,但它没有帮助。非常令人沮丧 - 当我提取失败的单行时,stringr 函数再次起作用。
    • 快速更新:如果我将我的数据集分成大约 3000 行的块,该函数可以工作。
    猜你喜欢
    • 2019-06-06
    • 2017-01-28
    • 2011-04-28
    • 2020-09-02
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    相关资源
    最近更新 更多