将中间输出分配给临时变量作为 dplyr 管道的一部分 [英] Assign intermediate output to temp variable as part of dplyr pipeline

查看:15
本文介绍了将中间输出分配给临时变量作为 dplyr 管道的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:在 R dplyr 管道中,我如何将一些中间输出分配给临时变量以供管道进一步使用?

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(); . } %>% 

这篇关于将中间输出分配给临时变量作为 dplyr 管道的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆