【问题标题】:Why is lapply not forwarding additional arguments?为什么 lapply 不转发其他参数?
【发布时间】:2020-12-21 17:09:17
【问题描述】:

我有一个大的推文数据集,其中每一行都是一个唯一的推文,并且我有一个关键字列表,如果其中一个或多个存在于变量 text中,我想从这些推文中提取这些关键字>。此关键字列表已编译为正则表达式(保存在变量 search_key 中),包括一些环视和其他条件。

如果使用以下代码,字符串的提取将非常有效:

data$keyword <- stri_extract_all(str = data$text, regex = search_key)

但为了优化/并行化代码,我想使用 apply 系列的函数。但是在执行以下任一行时,我总是会收到错误消息,因为 regex-参数未传递给 stri_extract_all-函数:

data$keyword <- lapply(data$text, FUN = stri_extract_all(), regex = search_key)
data$keyword <- lapply(data$text, FUN = stri_extract_all(), regex = get(search_key))
data$keyword <- lapply(data$text, FUN = stri_extract_all(), ... = "regex=search_key")

此行为独立于 search_keytext 变量的内容发生,因此任何文本列和任何工作正则表达式都可以用于测试。以下数据是我的数据的简化版,也可以使用:

data <- structure(list(status_id = c(1112765520644894720, 1112938379296104448, 
1112587129622876160, 1113006196259196928, 1112840488208531456
), text = c("@LaraFukuro more frilly stuff but i actually found a matching carrot bag which also screamed \"LARA\" inside me xD", 
"@EuroMasochismo @VaeVictis @AlbertoBagnai @Comunardo La selezione fatta a dodici anni favorisce chi è seguito. È come selezionare a 4 anni chi deve giocare a pallone proibendolo a tutti gli altri ...", 
"@SignorErnesto @Cr1st14nM3s14n0 @ggargiulo3 @micheleboldrin Sbagliato io.", 
"@BrownResearchGT On Aconcagua, the permit requires climbers above basecamp to collect their waste and carry it back down where it's taken away by helicopter. They actually weigh the bag! And still, most small rocks had human feces underneath. It's a problem!\r\nHopefully @DenaliNPS will follow suit. ", 
"@Jenn198523 Once you silence a person &amp; cover them with a huge trash bag, beating &amp; killing are not far behind."
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))

search_key <- "(?<=(^|\\s|\\D))([:alnum:]*|@[:alnum:]*|#[:alnum:]*)bag([:alnum:]*)(?=(\\D|\\s|$))"


 
我犯了什么错误,如何解决?
当然也欢迎任何关于优化此类任务的建议。

【问题讨论】:

  • 删除(),如lapply(data$text, FUN = stri_extract_all, regex = search_key)

标签: r apply lapply stringi


【解决方案1】:

stri_extract_all 已在 str 上进行矢量化。您不需要将其包含在 lapply 中,如果这样做会大大降低您的代码速度。

data$keyword <- stri_extract_all(data$text, regex = search_key)

【讨论】:

  • 非常感谢您的澄清!我只是注意到它在文档中是这样说的。你现在有什么方法可以并行化矢量化函数吗?还是有其他优化方法?
猜你喜欢
  • 1970-01-01
  • 2020-12-13
  • 2017-01-11
  • 1970-01-01
  • 2022-07-14
  • 2017-06-10
  • 2012-02-27
  • 2013-01-03
相关资源
最近更新 更多