簡體   English   中英

dplyr的函數,其參數默認為“。”

[英]function for dplyr with argument that defaults to “.”

假設我想將tibble中的所有列相加以創建一個名為“total”的新列。 我可以:

library(tibble)
library(dplyr)

set.seed(42)
N <- 10
Df <- tibble(p_1 = rnorm(N),
             p_2 = rnorm(N),
             q_1 = rnorm(N),
             q_2 = rnorm(N))

# Works fine
Df %>% mutate(total = apply(., 1, sum))

我可以像這樣制作一個幫助函數,

myfun <- function(Df){
  apply(Df, 1, sum)
}

# Works fine
Df %>% mutate(total = myfun(.))

但是,讓我們說這個myfun通常會以這種方式使用,即在dplyr動詞函數中,然后是“。”。 引用數據框是一個但是多余的,如果myfun函數可以用默認值替換它,那將會很好。 我想要這樣的事情:

myfun2 <- function(Df=.){
   apply(Df, 1, sum)
}

這不起作用。

Df %>% mutate(total = myfun2())
Error in mutate_impl(.data, dots) : 
 Evaluation error: object '.' not found.

因為我甚至不確定“。” 工作,我不認為我可以更好地表達問題,但基本上,我想知道是否有一種方式說,實際上,如果未在myfun2定義Df ,獲取通常由引用的數據幀“”?

一種選擇是quote該功能,然后評估!!

library(tidyverse)
myfun <- function() {
   quote(reduce(., `+`))
}

r1 <- Df %>% 
          mutate(total = !! myfun())
r1
# A tibble: 10 x 5
#       p_1    p_2    q_1     q_2  total
#     <dbl>  <dbl>  <dbl>   <dbl>  <dbl>
# 1  1.37    1.30  -0.307  0.455   2.82 
# 2 -0.565   2.29  -1.78   0.705   0.645
# 3  0.363  -1.39  -0.172  1.04   -0.163
# 4  0.633  -0.279  1.21  -0.609   0.960
# 5  0.404  -0.133  1.90   0.505   2.67 
# 6 -0.106   0.636 -0.430 -1.72   -1.62 
# 7  1.51   -0.284 -0.257 -0.784   0.186
# 8 -0.0947 -2.66  -1.76  -0.851  -5.37 
# 9  2.02   -2.44   0.460 -2.41   -2.38 
#10 -0.0627  1.32  -0.640  0.0361  0.654

請注意, reduce用於更多地與tidyverse對齊,但OP的功能也tidyverse並獲得相同的結果

myfun2 <- function() {
   quote(apply(., 1,  sum ))
}

r2 <- Df %>%
        mutate(total = !! myfun2())
all.equal(r2$total, r1$total)
#[1] TRUE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM