将中间输出分配给temp变量作为dplyr管道的一部分 [英] Assign intermediate output to temp variable as part of dplyr pipeline
问题描述
问:在R dplyr管道中,如何将一些中间输出分配给temp变量以在管道中进一步使用?
Q: In an R dplyr pipeline, how can I assign some intermediate output to a temp variable for use further down the pipeline?
我下面的方法行得通.但是它分配给全局框架,这是不可取的.必须有更好的方法,对吗?我认为涉及注释行的方法将获得预期的结果.没有骰子.感到困惑,为什么那行不通.
My approach below works. But it assigns into the global frame, which is undesirable. There has to be a better way, right? I figured my approach involving the commented line would get the desired results. No dice. Confused why that didn't work.
df <- data.frame(a = LETTERS[1:3], b=1:3)
df %>%
filter(b < 3) %>%
assign("tmp", ., envir = .GlobalEnv) %>% # works
#assign("tmp", .) %>% # doesn't work
mutate(b = b*2) %>%
bind_rows(tmp)
a b
1 A 2
2 B 4
3 A 1
4 B 2
推荐答案
这不会在全局环境中创建对象:
This does not create an object in the global environment:
df %>%
filter(b < 3) %>%
{
{ . -> tmp } %>%
mutate(b = b*2) %>%
bind_rows(tmp)
}
如果您使用. ->> tmp
代替. -> tmp
或将其插入到管道中,也可以将其用于调试:
This can also be used for debugging if you use . ->> tmp
instead of . -> tmp
or insert this into the pipeline:
{ browser(); . } %>%
这篇关于将中间输出分配给temp变量作为dplyr管道的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!