Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mutate() returns error about can't modify because it's a grouping variable

Tags:

r

dplyr

Error in mutate_impl(.data, dots) : 
  Column `month` can't be modified because it's a grouping variable

I would like to plot with one of the axis's being month of the year, however I would like it to go from August to July. I would also like "week" to display 1-5 instead of 5-1.....but it is not letting me do so when I try the following code:

Admit_Weekly1 <- Admit_Weekly %>% 
+   filter(Retention_Status == 1) %>% 
+   mutate(week = factor(week,levels(week)[1,2,3,4,5])) %>% 
+   mutate(month = factor(month,levels(month)["August","September","October","November",
+                                             "December","January","February","March",
+                                             "April", "May","June","July"]))

Error in mutate_impl(.data, dots) : Column week can't be modified because it's a grouping variable

like image 880
John Thomas Avatar asked Sep 14 '25 15:09

John Thomas


2 Answers

I ran into the same problem and solved it using the ungroup():

df <- df %>%
ungroup(var) %>%
mutate(var = factor(var,levels = c(1,2,3),
                    labels = c("label1","label2","label3") ) )


like image 183
Prof Gaëlle Avatar answered Sep 16 '25 04:09

Prof Gaëlle


In my case I realized I was using dplyr 0.8.5 instead of dplyr 1.0.7. Once I did the update of the package (o reinstall it) it worked without adding the ungroup() %>% line.

like image 43
Corina Roca Avatar answered Sep 16 '25 04:09

Corina Roca