Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters into function that uses dplyr

Tags:

r

dplyr

I have the following function to describe a variable

library(dplyr)
describe = function(.data, variable){
  args <- as.list(match.call())
  evalue = eval(args$variable, .data)
  summarise(.data,
            'n'= length(evalue),
            'mean' = mean(evalue),
            'sd' = sd(evalue))
}

I want to use dplyr for describing the variable.

set.seed(1)
df = data.frame(
  'g' = sample(1:3, 100, replace=T),
  'x1' = rnorm(100),
  'x2' = rnorm(100)
)
df %>% describe(x1)
#     n        mean        sd
# 1 100 -0.01757949 0.9400179

The problem is that when I try to apply the same descrptive using function group_by the describe function is not applied in each group

df %>% group_by(g) %>% describe(x1)
# # A tibble: 3 x 4
#       g     n        mean        sd
#   <int> <int>       <dbl>     <dbl>
# 1     1   100 -0.01757949 0.9400179
# 2     2   100 -0.01757949 0.9400179
# 3     3   100 -0.01757949 0.9400179

How would you change the function to obtain what is desired using an small number of modifications?

like image 739
marc1s Avatar asked Oct 23 '17 12:10

marc1s


People also ask

What does %>% do in dplyr?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

Can you pass functions as parameters in R?

In R programming, functions can be passed to another functions as arguments.

How many functions are there in dplyr?

These five functions provide the basis of a language of data manipulation.


1 Answers

You need tidyeval:

describe = function(.data, variable){
  evalue = enquo(variable)
  summarise(.data,
            'n'= length(!!evalue),
            'mean' = mean(!!evalue),
            'sd' = sd(!!evalue))
}

df %>% group_by(g) %>% describe(x1)
# A tibble: 3 x 4
      g     n        mean        sd
  <int> <int>       <dbl>     <dbl>
1     1    27 -0.23852862 1.0597510
2     2    38  0.11327236 0.8470885
3     3    35  0.01079926 0.9351509

The dplyr vignette 'Programming with dplyr' has a thorough description of using enquo and !!

Edit:

In response to Axeman's comment, I'm not 100% why the group_by and describe does not work here. However, using debugonce with the funciton in it's original form

debugonce(describe)

df %>% group_by(g) %>% describe(x1)

one can see that evalue is not grouped and is just a numeric vector of length 100.

like image 97
r.bot Avatar answered Oct 31 '22 04:10

r.bot