r - 将函数调用向量折叠成一行,用 & 分隔每个调用,使用替代和归约?
问题描述
我正在尝试构建函数调用str_detect(words, "a") & str_detect(words, "e") & str_detect(words, "i") & str_detect(words, "o") & str_detect(words, "u")
,而无需进行所有痛苦的打字。我知道这不是解决问题的好方法,但是在用更好的方法解决问题做得不好之后,我决定尝试这样做,看看我是否可以从中学到任何东西。
我的尝试如下:
library(stringr)
funList <- sapply(c("a", "e", "i", "o", "u"), function(y) substitute(str_detect(words, x), list(x=y)))
Reduce(function(a,b) paste(a, "&", b), funList)
这几乎奏效了。funList
几乎是我们所期望的:
> funList
$a
str_detect(words, "a")
$e
str_detect(words, "e")
$i
str_detect(words, "i")
$o
str_detect(words, "o")
$u
str_detect(words, "u")
但是最后一行给出了一些非常出乎意料的输出,大概是由于 R 构造函数调用的方式:
> Reduce(function(a,b) paste(a, "&", b), funList)
[1] "str_detect & str_detect & str_detect & str_detect & str_detect"
[2] "words & words & words & words & words"
[3] "a & e & i & o & u"
这可以修复以提供预期的函数调用吗?我尝试了一些技巧,比如抛出quote
函数,但我没有取得任何成就。
解决方案
funList
您可以通过以下方式实现预期的输出-
paste(funList, collapse = ' & ')
#[1] "str_detect(words, \"a\") & str_detect(words, \"e\") & str_detect(words, \"i\") & str_detect(words, \"o\") & str_detect(words, \"u\")"
但是,您不需要像您一样sapply
构建funList
-
paste0(sprintf('str_detect(words, "%s")', c("a", "e", "i", "o", "u")), collapse = ' & ')
#[1] "str_detect(words, \"a\") & str_detect(words, \"e\") & str_detect(words, \"i\") & str_detect(words, \"o\") & str_detect(words, \"u\")"
推荐阅读
- c# - RadGridView 按钮列内容绑定到 DataMember
- wordpress - Woocommerce“新订单”电子邮件未发送
- java - 将 PHP 服务器套接字连接到 Android 客户端套接字
- mysql - 是否可以跨多种语言设置 ASP Classic 和 MYSQL 的数字格式?
- git - 当前修改和另一个参考之间的 Git 差异
- scala - 如何计算 Spark 数据集 w 中的平均向量。斯卡拉?
- sql - 在 sqlite3 中使用 row_number 时出现语法错误
- c# - 嵌套调用不会触发拦截器
- azure-eventhub - 如何通过python向事件中心发送消息
- angular - 如何在角度服务中通过 API 获取 PDF