r - Unexpected '=' while using group_by and mutate to add a new column based on multiple conditions

Viewed 370

I want to group my dataset according to 2 columns (A, B), and then calculate the means of a 3rd column (C) based on those sub-groups.

Here is my code:

data %>% 
  group_by(A, B) %>%
  mutate(data$my_new_column = mean(C))

I get an error stating that there is an unexpected '=' in "group_by(A, B) %>% mutate(data$my_new_column ="

Any idea? Thankss

1 Answers

If we are creating a new column, just remove data$

library(dplyr)
data %>% 
  group_by(A, B) %>%
  mutate(my_new_column = mean(C, na.rm = TRUE))
Related