将数据框列作为参数传递给mutate函数

时间:2019-03-01 07:56:55

标签: r function dplyr tidyeval

我有一张表,其中有五列,分别是年,GDP,收入,收入和工资。我用此表通过以下代码进行计算。

library(dplyr)

#DATA
TEST<-data.frame(
  Year= c(2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021),
  GDP =c(8634,5798,6022,6002,6266,6478,6732,7224,6956,6968,7098,7620,7642,8203,9856,20328,22364,22222,23250,25250,26250,27250),
  Revenue =c(8734,5798,7011,7002,7177,7478,7731,7114,7957,7978,7098,7710,7742,8203,9857,10328,11374,12211,13150,15150,17150,17150),
  Income =c(8834,5898,6033,6002,6366,6488,6833,8334,6956,6968,8098,8630,8642,8203,9856,30328,33364,32233,33350,35350,36350,38350),
  Wages =c(8834,5598,8044,8002,8488,8458,8534,5444,8958,8988,5098,5840,5842,8203,9858,40328,44384,42244,43450,45450,48450,45450)
   )

#CALCULATION
    ESTIMATION_0<-data.frame(mutate(TEST,
                     ETR_Revenue=(Revenue/GDP),
                     ETR_Income=(Income/GDP),
                     ETR_Wages=(Wages/GDP)
              ))

View(ESTIMATION_0)

但是我的意图是使用一些自己的函数来优化此代码,例如fun2 <-function(x,y){((x / y))},该函数可以将收入除以GDP,将收入除以GDP等。那么有人可以帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

使用类似于answer

的整洁评估方法
library(rlang)
library(tidyverse)

my_estimate <- function(df, .pre, .deno, ...) {

  # capture the denumenator
  deno <- enquo(.deno)  
  # capture all numerator variables forwared by the dot-dot-dot
  nume <- enquos(...)

  result <- df %>% 
    # unquote numerator & denumenator using !!! and !!
    # create new variables with the suffix ".pre"
    mutate_at(vars(!!!nume), funs(!!sym(.pre) := . /(!!deno))) %>% 
    # rename newly created variables, ".pre" become prefix
    rename_at(vars(ends_with(.pre)), funs(paste(.pre, gsub(paste0("_", .pre), "", .), sep = "_")))

  return(result)
}

my_estimate(TEST, "ETR", GDP, Revenue, Income, Wages)

#> # A tibble: 22 x 8
#>     Year   GDP Revenue Income Wages ETR_Revenue ETR_Income ETR_Wages
#>    <dbl> <dbl>   <dbl>  <dbl> <dbl>       <dbl>      <dbl>     <dbl>
#>  1  2000  8634    8734   8834  8834       1.01        1.02     1.02 
#>  2  2001  5798    5798   5898  5598       1           1.02     0.966
#>  3  2002  6022    7011   6033  8044       1.16        1.00     1.34 
#>  4  2003  6002    7002   6002  8002       1.17        1        1.33 
#>  5  2004  6266    7177   6366  8488       1.15        1.02     1.35 
#>  6  2005  6478    7478   6488  8458       1.15        1.00     1.31 
#>  7  2006  6732    7731   6833  8534       1.15        1.02     1.27 
#>  8  2007  7224    7114   8334  5444       0.985       1.15     0.754
#>  9  2008  6956    7957   6956  8958       1.14        1        1.29 
#> 10  2009  6968    7978   6968  8988       1.14        1        1.29 
#> # ... with 12 more rows

reprex package(v0.2.1.9000)于2019-03-01创建