Programming with dplyr 0.5.0

This code works with dplyr 0.7.4, following the 'programming with dplyr' vignette.

Unfortunately, the rstudio server I use at work has dplyr 0.5.0, I do not have the ability to upgrade the package.

With 0.5.0 the code fails with "error: invalid argument type"

What modifications are necessary to 'backport' my function?

library(lubridate)
library(dplyr)
library(rlang)
samp <- tbl_df(seq.Date(as.Date("2017-01-01"), as.Date("2017-12-01"), by="day"))

count_x_month <- function(df, var, name){
  var <- enquo(var)
  name <- enquo(name)
  name <- quo_name(name)
  
  df %>%
    filter(!is.na(!!var)) %>% 
    transmute(month := floor_date(!!var, "month")) %>%
    group_by(month) %>% 
    summarise(!!name := n())
} 

freq2 <- samp %>% count_x_month(value, out)
freq2

tidyeval was introduced in dplyr 0.7.0, if you want to program with dplyr 0.5.0 you will probably need to use the functions with underscores after them (i.e. mutate_() - I am not sure the naming convention for these functions.) These will let you pass character strings to the functions so you can create generic functions with them. However, you won't be able to use quosures with these functions (at least not to my knowledge)

2 Likes

Also, does the code have to run under a different account than your own on the server? Or do you have policies in place that prevent non-approved packages? Otherwise, I think you should be able to install an updated version of the package in your local package directory, just like you would for a package that you are missing.

1 Like

r version 3.2 installed :frowning:

1 Like

Which package requires a newer version? dplyr only requires 3.1.2 or newer, though I suspect one or two dependencies may require a newer version. You may still be able to work around that by carefully installing appropriate older versions, though.

1 Like

You will need to use the lazyeval package/ functions I think.

I found this gist helpful in understanding lazyeval with dplyr 5.0

I have some other examples if you need them. On my phone just now so can't upload at present.

1 Like

Hi @jcress410,

In the help for the rlang functions, they mention which base R function the new functions are based on. Using that I tried my best at getting you some working code, hopefully this gets you going:



library(dplyr)


samp <- tbl_df(seq.Date(as.Date("2017-01-01"), as.Date("2017-12-01"), by="day"))

count_x_month <- function(df, var, name){
  
  char_var <- as.character(substitute(var))
  char_name <- as.character(substitute(name))
  var  <- deparse(substitute(var))
  
  
  
  df <- df %>%
    mutate_("x" = char_var) %>%
    mutate(x = month(x)) %>%
    filter(!is.na(var)) %>%
    group_by(x) %>%
    summarise(n())

  colnames(df) <- c("month", char_name)
  
  
  df
} 

freq2 <- samp %>% count_x_month(value, out)
freq2

3 Likes