代码之家  ›  专栏  ›  技术社区  ›  J. Mini

将函数调用的向量折叠到一行中,用&分隔每个调用,使用substitute和Reduce?

  •  0
  • J. Mini  · 技术社区  · 4 年前

    我正在尝试构造函数调用 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,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 但我什么都没做。

    2 回复  |  直到 4 年前
        1
  •  1
  •   Roland    4 年前

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

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

    funList <- lapply(c("a", "e", "i", "o", "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")
    
        2
  •  1
  •   Ronak Shah    4 年前

    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 建造 幽默列表 尽你所能-

    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\")"
    
    推荐文章