% is.na() #[1] FALSE "test" %>% nchar(-6ren">
gpt4 book ai didi

r - 使用 magrittr 管道转发运算符两次传递参数

转载 作者:行者123 更新时间:2023-12-04 11:04:05 26 4
gpt4 key购买 nike

这是困扰我的一个虚拟示例(在 vanilla session 中):

library(magrittr)
"test" %>% is.na()
#[1] FALSE
"test" %>% nchar()>3
#[1] TRUE
"test" %>% is.na(.)
#[1] FALSE
"test" %>% nchar(.)>3
#[1] TRUE
"test" %>% is.na(.) || nchar(.)>3
#Error in nchar(.) : object '.' not found

到目前为止,我的理解是 .运算符(不知道运算符这个词是否准确,但让我们使用它)只能在管道转发之后调用的第一个函数中使用。
useless_function <- function(a, b, c) {
print(c(a,b,c))
return(FALSE)
}
"test" %>% useless_function(1, "a")
#[1] "test" "1" "a"
#[1] FALSE
"test" %>% useless_function(1, "a", .)
#[1] "1" "a" "test"
#[1] FALSE
"test" %>% useless_function(., ., "a")
#[1] "test" "test" "a"
#[1] FALSE
"test" %>% useless_function("a", ., useless_function(1, 2, .))
#[1] "1" "2" "test"
#[1] "a" "test" "FALSE"
#[1] FALSE
"test" %>% useless_function("a", ., useless_function(1, 2, .)) || useless_function(., "never", "here")
#[1] "1" "2" "test"
#[1] "a" "test" "FALSE"
#Error in print(c(a, b, c)) : object '.' not found

所以,我尝试使用 magrittr::or功能:
> "test" %>% or(is.na(.), nchar(.)>3)
#Error in or(., is.na(.), nchar(.) > 3) :
# 3 arguments passed to '|' which requires 2

这几乎就是我被困的地方。

请注意,我知道解决此问题的几种方法。只是,它们中没有一个像正常的管道转发功能一样清晰。
("test" %>% is.na()) | ("test" %>% nchar()>3)
#[1] TRUE
"test" ->.; is.na(.) | nchar(.)>3 # Don't hit me, this one is just for fun
#[1] TRUE

最佳答案

使用 {}指定优先级,以便按照您想要的方式评估它们

library(magrittr)

"test" %>% {is.na(.) || nchar(.)>3}
#[1] TRUE

或者
"test" %>% {or(is.na(.), nchar(.)>3)}

关于r - 使用 magrittr 管道转发运算符两次传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58814294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com