gpt4 book ai didi

r - magrittr 管道不计算一个点通过函数参数中的第二个管道

转载 作者:行者123 更新时间:2023-12-04 12:35:44 27 4
gpt4 key购买 nike

当第二次使用点重用管道左侧的数据时,将点传递给函数 . %>% f()与将点放在函数括号内不同 f(.) .为什么是这样?

调试 %>% 运算符表明 . %>% identity() 计算为函数序列而不是字符向量,这会导致 names<-失败。我不知道如何强制评估这个。

# Error
c('a', 'b', 'c') %>% `names<-`(., . %>% identity())
# Works
c('a', 'b', 'c') %>% `names<-`(., identity(.))
c('a', 'b', 'c') %>% `names<-`(., . %>% identity())

Error in as.vector(x, "character") : cannot coerce type 'closure' to vector of type 'character'


c('a', 'b', 'c') %>% `names<-`(., identity(.))
# a b c
#"a" "b" "c"

最佳答案

. 开头的管道生成一个函数。

例如,. %>% identityfunction(.) identity(.) 相同.

因此,

# Error
c('a', 'b', 'c') %>% `names<-`(., . %>% identity())

被视为

c('a', 'b', 'c') %>% `names<-`(., function(.) identity(.))

这意味着 names<- 的第二个参数是函数,而不是字符向量。

这记录在 Using the dot-place holder as lhs 中.

为了解决方法,请尝试

c('a', 'b', 'c') %>% `names<-`(., (.) %>% identity())

关于r - magrittr 管道不计算一个点通过函数参数中的第二个管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195618/

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