hafen / trelliscopejs

TrelliscopeJS R Package
https://hafen.github.io/trelliscopejs
Other
263 stars 36 forks source link

Error when using map_cog with factor variable #72

Closed lmbramer closed 5 years ago

lmbramer commented 5 years ago

When I try to use map_cog to add a data.frame of cognostics, a call to building the trelliscope display errors out:

library(dplyr)
library(trelliscopejs)
library(ggplot2)
library(tidyr)
library(purrr)

mycog_fn <- function(x){
  data.frame(max_city_mpg = cog(max(x$cty), desc = "Max city mpg"),
  min_city_mpg = cog(min(x$cty), desc = "Min city mpg"),
  first_drv = cog(x$drv[1], desc = "factor variable")
  )
}

myplot_fn <- function(x){
  ggplot(data = x, aes(x = cty, y = hwy)) +
    geom_point()
}

ggplot2::mpg %>% group_by(manufacturer, class) %>% nest() %>% mutate(cogs = map_cog(data, mycog_fn), panel = map_plot(data, myplot_fn)) %>% trelliscope(path = "mypath")

I get the following error:

Error in attributes(res[[nm]]) <- one_row_attrs[[nm]] : 
  adding class "factor" to an invalid object
> traceback()
12: bind_cog_list_and_descs(to_auto_list)
11: cog_df_info(x, panel_col = panel_col, state = state, auto_cog = auto_cog)
10: trelliscope.data.frame(., path = "/Users/bram489/Desktop/test2")
9: trelliscope(., path = "/Users/bram489/Desktop/test2")
8: function_list[[k]](value)
7: withVisible(function_list[[k]](value))
6: freduce(value, `_function_list`)
5: `_fseq`(`_lhs`)
4: eval(quote(`_fseq`(`_lhs`)), env, env)
3: eval(quote(`_fseq`(`_lhs`)), env, env)
2: withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
1: ggplot2::mpg %>% group_by(manufacturer, class) %>% nest() %>% 
       mutate(cogs = map_cog(data, mycog_fn), panel = map_plot(data, 
           myplot_fn)) %>% trelliscope(path = "/Users/bram489/Desktop/test2")

It seems that bind_cog_list_and_descs is attempting to pull column attributes for each cognostic from a single row, and update the attributes of the result of calling bind_rows on the list of cognostics. However, factor variables don't seem to retain any attributes when bind_rows is called.

hafen commented 5 years ago

Thanks for submitting this. I have fixed this so that it doesn't fail. However, when someone uses cog() inside data.frame() when adding a cognostics column and doesn't specify stringsAsFactors = FALSE, any custom cognostics attributes (such as the description) will be lost. I have added a note when such a case is detected. It's probably best to just use tibble() instead of data.frame().