0

Suppose I have a data.frame df like this:

df <- tribble(
  ~id,  ~name,  ~group,      ~score,      
  01,  "john",  "group_1",      80,
  01,  "john",  "group_3",      85,
  01,  "john",  "group_2",      75,
  02,  "adam",  "group_2",      80,
  02,  "adam",  "group_1",      85
)

I want to find the individual sums for the score of each group and store them in a new variable, for example, the variable avg_group_1 should have the value 82.5. (because the group_1 scores are 80 and 85)

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
Gops82
  • 23
  • 2

2 Answers2

1

You can use this. I assumed you want to group your data with group column values.

library(dplyr)

data <- tribble(
  ~id,  ~name,  ~group,      ~score,      
  01,  "john",  "group_1",      80,
  01,  "john",  "group_3",      85,
  01,  "john",  "group_2",      75,
  02,  "adam",  "group_2",      80,
  02,  "adam",  "group_1",      85
)

data %>% 
  group_by(group) %>%
  summarise(avg = mean(score, na.rm = TRUE))

# A tibble: 3 x 2
  group     avg
  <chr>   <dbl>
1 group_1  82.5
2 group_2  77.5
3 group_3  85 

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
1

in addition . to create a new column to data. this is my first answer from my android. it is a little clumsy.

data %>% 
  group_by(group) %>%
  mutate(avg = mean(score, na.rm = TRUE))
TarJae
  • 72,363
  • 6
  • 19
  • 66