Miao  Cai
Miao Cai

Reputation: 1014

"Error in eval(bysub, x, parent.frame()) : object '.x' not found" when using data.table function within purrr::map_dfr()

When I'm using a data.table aggregation function within purrr::map_dfr(), I encountered this error message Error in eval(bysub, x, parent.frame()) : object '.x' not found, but I have no clue how this error come about. Below is a minimal reproducible example.

library(data.table)
library(purrr)

df = as.data.table(mtcars)

ffreq = function(group, data = df){
  group = substitute(group)
  return(data[,.(N = .N),eval(group)])
}

# These functions work
ffreq('mpg')
ffreq('gear')

# This one within map_dfr does not work

d_all = map_dfr(names(df), ffreq)
# Error in eval(bysub, x, parent.frame()) : object '.x' not found

Any suggestion would be greatly appreciated

Upvotes: 1

Views: 2099

Answers (1)

s_baldur
s_baldur

Reputation: 33538

The following is enough since by accepts character vectors:

ffreq = function(group, data = df) data[, .N, group]

Also you could do all this without purrr:

groupingsets(df, j = .N, by = names(df), sets = as.list(names(df)))

Or

rbindlist(lapply(names(df), ffreq), fill = TRUE)

Upvotes: 4

Related Questions