0

I'd like to write a function that calculate a mean of a given variable with using dplyr function. I tried following concept with many modifications but were not succesful. Should one avoid dplyr functions within own functions? or is there any trick that do the thing?

df <- data.frame(type = c("KL", "KL", "A", "A", "B", "B"), 
                 D10 = rnorm(6, 3, 4))

licz <- function(dat, trait){
  require("dplyr")
  dat %>% group_by_(type) %>% summarise(sr = mean(trait, na.rm = T)) -> dataset
  return(dataset)
}

licz(df, D10)
zx8754
  • 52,746
  • 12
  • 114
  • 209
Mateusz1981
  • 1,817
  • 17
  • 33
  • 6
    https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html – mt1022 Nov 22 '16 at 07:18
  • 1
    `licz <- function(dat, trait){ dat %>% group_by_(~type) %>% summarise_(sr = lazyeval::interp(~mean(x, na.rm = T), x = as.name(trait))) } ;licz(df, 'D10')` – Axeman Nov 22 '16 at 08:06
  • Thx @Axeman, it works fine, and I guess it is much easier example to understand for beginners and noprogrammers than the one in the link that indicate duplication – Mateusz1981 Nov 22 '16 at 14:41

0 Answers0