0

Fairly new R user here, just now getting into more advanced material. I am writing a simple function that utilizes the arrange function in the dplyr package. The function intends to filter a dataframe using partial string matching and then sort the result on a column specified by the 'sortby' argument in the function. Here is what I have thus far:

calcs <- function(data, type, sortby) {
filt <- data[grep(type, data$name), ]
ord <- dplyr::arrange(filt, desc(sortby))
return(ord)
}

The sortby variable is not being found when evaluated. I am speculating that it has something to do with standard and non-standard evaluation, but this is a bit outside my programming aptitude.

Here is a reproducible example:

mydata <- data.frame(name=c("GI Joe", "GI Joe", "Batman", "Xbox"),
                     rating=c(8,12,8,1))

calcs(data=mydata, type="GI", sortby=rating)

Error in desc(sortby) : object 'rating' not found

To be clear, my goal with this function is to filter a dataset using partial string matching and to sort the result on a column of interest.

Danny Morris
  • 82
  • 1
  • 6

2 Answers2

0

You should rewrite your function to use NSE. On usage of NSE see this post and take a look at vignette('nse') in R.

calcs <- function(data, type, sortby) {
    sorting <- paste0('desc(', sortby, ')') #nse
    filt <- data[grep(type, data$name),]
    ord <- dplyr::arrange_(filt, .dots = sorting) #use arrange_
    return(ord)
}

mydata <- data.frame(name = c("GI Joe", "GI Joe", "Batman", "Xbox"),
                     rating = c(8,12,8,1))

calcs(data = mydata, type = "GI", sortby = 'rating')

    name rating
1 GI Joe     12
2 GI Joe      8
Community
  • 1
  • 1
bouncyball
  • 10,631
  • 19
  • 31
0

The tidyverse package functions have changed a bit. Instead of using arrange_(), you need to add a line transforming the object. See the programming vignette:

https://tidyeval.tidyverse.org/sec-up-to-speed.html

From that vignette, they have the following example of how to include column names for dplyr() functions inside of a package:

grouped_mean <- function(data, group_var, summary_var) {
  group_var <- enquo(group_var)
  summary_var <- enquo(summary_var)

  data %>%
    group_by(!!group_var) %>%
    summarise(mean = mean(!!summary_var))
}

grouped_mean(mtcars, cyl, mpg)
K Bro
  • 359
  • 3
  • 6