gpt4 book ai didi

r - 在封闭件内使用 magrittr 管

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

1让我们看看这个例子:

1:3 %>% rep(.,2) + 1 %>% sum  #[1] 2 3 4 2 3 4

[2] R 正在做的是:
1:3 %>% rep(.,2) + (1 %>% sum)

[3] 我想让 R 做的是:(给出错误),我喜欢得到 18那里。
1:3 %>% (rep(.,2) + 1) %>% sum  #Error in rep(., 2) : attempt to replicate an object of type 'closure'

[4] 所以我需要变得 super 蹩脚:
tmp <- 1:3 %>% rep(.,2) + 1
tmp %>% sum #[1] 18

我怎样才能修复 [3] 工作。有人可以向我解释错误消息吗?

编辑

来自 here

Note that the variable x on the left side of %>% is applied as the first argument in the function on the right side. This default behaviour can be changed using . which is called a placeholder.

However, one important thing to remember is, when the . appears in nested expressions, the first-argument-rule is still applied. But this behaviour can be suppressed using the curly braces{ }



有趣的是,我不知道的是:

这是相等的:
1:3 %>% sum(rep(.,3))   #[1] 24
1:3 %>% sum(.,rep(.,3)) #[1] 24

这两个是相等的:
1:3 %>% {sum(rep(.,3))}  #[1] 18
1:3 %>% rep(.,3) %>% sum #[1] 18

编辑2
> packageVersion("magrittr")
[1] ‘1.5’

这个:
?'%>%'

给出:(我不知道我的 %>% 操作符背后是什么包,老实说我不太喜欢那个)

Help on topic '%>%' was found in the following packages:

Pipe operator (in package tidyr in library C:/Program Files/R/R-3.3.2/library) magrittr forward-pipe operator (in package magrittr in library C:/Program Files/R/R-3.3.2/library) Pipe operator (in package stringr in library C:/Program Files/R/R-3.3.2/library) Objects exported from other packages (in package dplyr in library C:/Program Files/R/R-3.3.2/library)

最佳答案

二元运算符 +正在制造问题。它的优先级低于管道(见 ?Syntax)。要么在管道求和之前将整个操作括在括号中,要么使用 + 的函数形式:

(1:3 %>% rep(.,2) + 1) %>% sum
[1] 18

1:3 %>% rep(.,2) %>% `+`(1) %>% sum
[1] 18

关于r - 在封闭件内使用 magrittr 管,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48769061/

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