在 r 中如何使用数据框的 2 个部分作为函数的参数来制作管道?

In r how to make a pipeline with 2 parts of a data frame as parameters of a function?

我正在尝试做一个像这样的管道:

df <- df %>% 
         .....some functions pass df as first parameter....
         zoo(???) %>%
          .....some functions pass df as first parameter....

因为在步骤 zoo() 中,它需要 df[ some_columns] 作为第一个参数,df$a_index 作为第二列,我如何写入这个管道?如果我不想将管道分成:

df <- df %>% .... 
df <- zoo(df[, some_columns], df$a_index)
df <- df %>% .... 

1) 以内置 BOD 数据框为例,最简单的方法是使用 read.zoo 形成动物园对象,如下所示:

library(dplyr) # library(magrittr) would also work for this example
library(ggplot2)
library(zoo)

BOD %>%
    read.zoo() %>%
    autoplot()

2) 然而,如果你真的想使用 zoo 构造函数,那么这个是可行的(使用相同的 library 语句):

BOD %>% 
    { zoo(.[[[2]], .[[1]]) } %>% 
    autoplot()

如果 BOD 有超过 2 列,则使用 .[-1] 作为第一个参数。

3)这也行。

BOD %>%
    { zoo(.$demand, .$Time) } %>%
    autoplot

4) 这也有效:

library(magrittr) # must use magrittr

BOD %$%  # note that this is a different pipe operator
    zoo(demand, Time) %>%
    autoplot()