function with variable column name

Viewed 56

I have a function that I repeatedly use to summarize information for individuals (with unique ID's within my datasets. Due to how this data is arranged, sometimes the ID column has one name, and other times it has another name. Rather than having different functions for each dataset, I'm trying have an IDtype field in my function so I can specify the column in each dataset where the ID field is located. However, I keep getting the following error for my function below:

fun <- function(df, IDtype) {
  df %>%
    group_by(species, IDtype, site) %>%
    summarize(tsMean = mean(ts)) %>%
    arrange(IDtype, tsMean)
}

dfSum <- (fun(data, IDtype = id) #also tried with id in quotes ("id"), but I get the same error 

Error: Column `IDtype` is unknown 

How do I fix this function?

2 Answers

For people interested in data.table, the following syntax can be used:

library(data.table)
fun <- function(df, IDtype){
   return(
      df[, .(tsMean = mean(ts)), by = c("species", IDtype, "site")][order(get(IDtype), get("tsMean")]
      )
}
setDT(data)
fun(data, IDtype = "id")

You unquote names with the get() function

We can use the curly-curly operator ({{}}) to evaluate the unquoted value

fun <- function(df, IDtype) {
  df %>%
     group_by(species, {{IDtype}}, site) %>%
     summarize(tsMean = mean(ts)) %>%
     arrange({{IDtype}}, tsMean)
    }

fun(data, IDtype = id)
Related