r - 为什么 lapply 不转发其他参数?
问题描述
我有一个大的推文数据集,其中每一行都是一个唯一的推文,并且我有一个关键字列表,如果变量text中存在一个或多个,我想从这些推文中提取这些关键字。此关键字列表已编译为正则表达式(保存在变量search_key中),包括一些环视和其他条件。
如果使用以下代码,则字符串的提取工作得非常好:
data$keyword <- stri_extract_all(str = data$text, regex = search_key)
但是为了优化/并行化代码,我想使用 apply 系列的函数。但是在执行以下行之一时,我总是会收到错误消息,因为regex -argument 未传递给stri_extract_all -function:
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_key和text变量的内容发生,因此任何文本列和任何工作正则表达式都可以用于测试。以下数据是我的数据的简化版本,也可以使用:
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 & cover them with a huge trash bag, beating & 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|$))"
我犯了什么错误,如何解决?
当然也欢迎任何关于优化此类任务的建议。
解决方案
stri_extract_all
已在 上矢量化str
。您不需要将其包含在内,lapply
如果您这样做,您将显着减慢您的代码。
data$keyword <- stri_extract_all(data$text, regex = search_key)
推荐阅读
- html - Bootstrap 3 布局,包括推/拉组合、一个 div“rowspan”和重新排序的移动 div
- meteor - Meteor 实时更新无法按预期工作
- google-analytics - 谷歌分析 gtag 应该如何在 SPA 中工作?
- javascript - 最佳实践:替换每个元素或仅检查和替换已更改的元素是否更有效?
- python - ipython控制台中的彩色熊猫数据框输出
- algorithm - 有人可以向我解释为什么完美平方是 O(sqrt(n)) 的运行时间吗?
- reactjs - 混合使用 React 和 Vue 是个好主意吗?
- javascript - 谷歌脚本邮件应用
- r - PCA 缩放不适用于个人?
- macos - 为使用 Electron 创建的 macOS 应用程序创建“Safari 应用程序扩展”?