Home > Blockchain >  Error in eval(bysub, x, parent.frame()) : object 'Year' not found
Error in eval(bysub, x, parent.frame()) : object 'Year' not found

Time:07-26

I am trying to write a function using R data.table syntax. It has results if I just run this line countbyYr = data[, .(counts = uniqueN(Col_A)), by = .(Year)], but once I put it into a function (shown below), it'll tell me Error in eval(bysub, x, parent.frame()) : object 'Year' not found.

counts_func <- function(df,groupby_col) {
  cnts<- df[, .(counts = uniqueN(Col_A)), by = .(groupby_col)]
  return(cnts)
}
countbyYr = counts_func(data,Year)

I've tried adding get() to get the column variable as some posts suggested, however, I'm still getting error messages.

CodePudding user response:

by can also take a vector of column names (or a single quoted colum name), so you can do this:

counts_func <- function(df,groupby_col) {
  df[, .(counts = uniqueN(Col_A)), by = groupby_col]
}
countbyYr = counts_func(data,"Year")

Alternatively, you can also use deparse(substitute()), as below

counts_func <- function(df,bycol) {
  bycol  = deparse(substitute(bycol))
  df[, .(counts = uniqueN(Col_A)), bycol]
}
counts_func(data,Year)
  • Related