0

I am attempting to create a segment column, or in other words make wide data long. I am running into an issue with iteratively creating a data frame to do this however.

mtcars.1 <- mtcars %>%
  mutate(mpg = ifelse(mpg <= 25,"MPG <= 25","MPG > 25")) %>%
  mutate(displ = ifelse(disp <= 200,"Disp <= 200","Disp > 200"))


cols <- as.list(c("displ","mpg"))
SegmentSpread <-  function(x) {
  x <- mtcars.1 %>%
    group_by(cyl,x) %>%
    summarise(Count = n())
  return(x)
}

lapply(cols, SegmentSpread)

I am wanting to return one data frame with the displacement and mpg segments in one segment column, and the count of each in another column along with cylinder being one column.

I realize I am way off here.

The output is:

 Error in grouped_df_impl(data, unname(vars), drop) : 
  Column `x` is unknown
Devin
  • 363
  • 2
  • 20
  • This is actually a weird issue with group_by when you pass variables. If you use `paste(x)`it works – Julian_Hn Mar 26 '19 at 20:16
  • It's not really a weird issue, it's specifically designed this way. And `paste` is not a recommended solution. You can't willy nilly mix standard and non-standard evaluation. For more details, see [the vignette](https://dplyr.tidyverse.org/articles/programming.html). – Axeman Mar 26 '19 at 20:30
  • (Also note that you can use `mtcars.1 %>% group_by(cyl) %>% count(mpg, displ)`.) – Axeman Mar 26 '19 at 20:35

0 Answers0