在管道中使用rbind可以使我不必定义和存储变量才能使用它吗?
library(tidyverse)
## works fine
df <- iris %>%
group_by(Species) %>%
summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
ungroup
df %>%
rbind(df)
## anyway to make this work?
iris %>%
group_by(Species) %>%
summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
ungroup %>%
rbind(.)发布于 2022-02-09 16:10:22
为了详细说明@MichaelDewar的答案,请注意?magrittr::`%>%`的以下部分
lhs
Placing in call
通常,您会希望lhs在比第一个位置更高的位置调用rhs。为此,您可以使用点(.)作为占位符。例如,y %>% f(x, .)等价于f(x, y),z %>% f(x, y, arg = .)等效于f(x, y, arg = z)。
我的理解是,当.作为参数出现在右侧调用时,左手侧不会插入第一个位置。调用被计算为“如实”,.计算到左手边。因此:
library("dplyr")
x <- data.frame(a = 1:2, b = 3:4)
x %>% rbind() # rbind(x)
## a b
## 1 1 3
## 2 2 4
x %>% rbind(.) # same
## a b
## 1 1 3
## 2 2 4
x %>% rbind(x) # rbind(x, x)
## a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4
x %>% rbind(x, .) # same
x %>% rbind(., x) # same
x %>% rbind(., .) # same
## a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4如果你知道规则,你就可以设计出聪明的把戏:
x %>% rbind((.)) # rbind(x, (x))
## a b
## 1 1 3
## 2 2 4
## 3 1 3
## 4 2 4(.)不像.那样被解析,所以左手被插入到右手侧调用的第一个位置。比较:
as.list(quote(.))
## [[1]]
## .
as.list(quote((.)))
## [[1]]
## `(`
##
## [[2]]
## .发布于 2022-02-09 15:27:43
我不知道你为什么要用自己的方式来rbind一些东西,但下面是这样的:
iris %>%
group_by(Species) %>%
summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
ungroup %>%
rbind(., .)https://stackoverflow.com/questions/71052259
复制相似问题