将函数调用向量折叠成一行,用 & 分隔每个调用,使用替代和减少?

问题描述

我正在尝试构造函数调用 str_detect(words,"a") & str_detect(words,"e") & str_detect(words,"i") & str_detect(words,"o") & str_detect(words,"u") 而不进行所有那些痛苦的输入。我知道这不是解决问题的好方法,但在 doing a poor job of solving it a better way 之后,我决定尝试这样做,看看我是否可以从中学到任何东西。

我的尝试如下:

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,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")),\"u\")"
,

这是一个非常糟糕的通用方法。您可能也不需要这样做。

但是,如果您继续在语言上进行计算并利用运算符实际上被解析为函数,那将非常容易:

funList <- lapply(c("a","u"),function(y) substitute(str_detect(words,x),list(x=y)))
Reduce(function(a,b) substitute(`&`(a,b),list(a = a,b = b)),funList)
#str_detect(words,"a") & str_detect(words,"e") & str_detect(words,#    "i") & str_detect(words,"o") & str_detect(words,"u")
,

我们可以使用str_c

library(stringr)
str_c(funList,collapse = ' & ')

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...