R管道(%&%;%)功能-存储和部分使用? [英] R pipe (%>%) capabilities - storage and partial use?

查看:76
本文介绍了R管道(%&%;%)功能-存储和部分使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢管道提高可读性的想法,但是由于感觉不够灵活,因此在使用它时遇到了困难。到目前为止,只有在我的目标是通过一组函数h(g(f(x,foo),bar),stuff)直接通过管道传递X时,我才成功

I like the idea of the pipe improving readability, but I've had difficulty using it because of how inflexible it feels. So far I've only succeeded when my goal is to straightforwardly pipe X through a set of functions h(g(f(x,foo),bar),stuff)

x %>%
f(foo) %>%
g(bar) %>%
h(stuff)

如果我想存储中间输出,以便可以拥有h(x,stuff,f(x,foo)),那可能吗?我已经尝试过

If I want to store an intermediate output so that I can have h(x,stuff,f(x,foo)), is that possible? I've tried

x %>% 
intermediate = f(foo) %>% 
g(bar)

但这会失败。分配不起作用,因为第一个参数是名称而不是值;

but that fails. Assign doesn't work because the first argument is the name rather than the value; is there an opposite equivalent?

我知道您可以使用。多次引用x或x的一部分,但是有没有办法最初只使用x的一部分?我想在不同的列上执行不同的功能,例如

I know you can use "." to refer to x or portions of it multiple times, but is there a way to use only a portion of it initially? I want to perform different functions on different columns, such as

data.frame(x[,1],apply(.[,2:3],2,fun1),apply(.[,4],2,fun2))

但是我不知道如何将第一个参数限制为仅 x [,1] 而不是所有 x 。我不能使用%>%select(1)%>%,因为那样它将永久删除其余部分。有没有办法做到这一点,还是我应该结束管道,执行这些功能并启动另一个管道?最简单的解决方案是将所有 x 放入数据框,然后%>%select(1,5:9)%> %

but I can't figure out how to limit the first argument to only x[,1] instead of all of x. I can't use %>% select(1) %>% because then it will drop the rest forever. Is there a way to do this or should I just end the pipe, do these functions, and start another pipeline? Is the easiest solution to just put all of x into the data frame and then %>% select(1,5:9) %>%?

推荐答案

您可以编写函数来执行可包含在链中的赋值。

You could write a function to do the assignment that you can include in the chain. Something like

save_to <- function(x, v) {
    var <- substitute(v)
    eval(bquote(.(var) <- .(x)), envir=globalenv())
    x
}


library(magrittr)
x<-1:10
f<-function(x) x+1
g<-function(x) x*2
h<-function(x) paste(x, collapse=", ")    

x %>% f %>% g %>% save_to(z) %>% h
# [1] "4, 6, 8, 10, 12, 14, 16, 18, 20, 22"
z
#  [1]  4  6  8 10 12 14 16 18 20 22

请注意,这会将值保存到全局环境中。因此,这可能不是一个好主意(具有副作用的功能通常是功能语言中的不良设计实践)。最好将其分解为不同的链。

Note that this saves the value to the global environment. For this reason it's probably not a great idea (functions with side effects are generally a bad design practice in functional languages). It would be better to break it up into different chains.

z <- x %>% f %>% g
z %>% h

这篇关于R管道(%&%;%)功能-存储和部分使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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