首页 > 解决方案 > 将函数调用向量折叠成一行,用 & 分隔每个调用,使用替代和归约?

问题描述

我正在尝试构建函数调用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函数,但我没有取得任何成就。

标签: rfunctionreducesubstitutionquote

解决方案


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

推荐阅读