【发布时间】:2018-11-13 03:55:17
【问题描述】:
我在一个表格中有数据,其中每一行中的一个单元格是一个多行字符串,其格式有点像末尾带有引用的文档。例如,其中一个字符串如下所示:
item A...1
item B...2
item C...3
item D...2
1=foo
2=bar
3=baz
我的最终目标是将 foo/bar/baz 提取到列中并计算匹配项。因此,对于上述内容,我最终会得到一行,包括:
foo | bar | baz
----+-----+----
1 | 2 | 1
我尝试从提取“参考”映射开始,作为嵌套的 data.table,如下所示:
code | reason
-----+-------
1 | foo
2 | bar
3 | baz
这是我尝试使用data.table 和stringr 的方法。
encounter_alerts[, whys := lapply(
str_extract_all(text, regex('^[0-9].*$', multiline = TRUE)),
FUN = function (s) { fread(text = s, sep = '=', header = FALSE, col.names = c('code', 'reason')) }
)]
我对尝试执行此操作时收到的错误消息感到非常困惑:
Error in fread(text = s, sep = "=", header = FALSE, col.names = c("code", :
file not found: 1=foo
我明确使用text 而不是file,所以我不确定它是如何将文本行解释为文件名的!
当我用一行测试它时,它似乎工作正常:
> fread(text = str_extract_all(encounter_alerts[989]$text, regex('^[0-9].*$', multiline = TRUE))[[1]], sep = '=', header = FALSE, col.names = c('code', 'reason'))
code reason
1: 1 foo
2: 2 bar
我做错了什么?有没有更好的方法来做到这一点?
谢谢!
【问题讨论】:
标签: r data.table