-1

In a data frame as input:

data.frame(group = c(1,1,1,2,2,3), number = c(10,10,10,5,5,1))

How is it possible to check which is the group number using the group column and calculate for every number the average score of the number column?

Example of expected output:

group avg_number

1     10
2      5
3      1
rek
  • 177
  • 7
  • 2
    You can use `aggregate` `aggregate(number ~ group, df1, FUN = mean)` – akrun Dec 20 '20 at 22:37
  • `aggregate` works well. If you don't like using formulas, you can use a grouped `tibble`. Load the `dplyr` package, then, assuming your data.frame is named `df` use: `df %>% group_by(group) %>% summarize(avg_number = mean(number))` – Geoffrey Poole Dec 20 '20 at 22:45

1 Answers1

1

You can use group_by from dplyr

data <- data.frame(group = c(1,1,1,2,2,3), number = c(10,10,10,5,5,1))
data %>% 
       group_by(group) %>%
         summarise(avg= mean(number), .groups='drop')

Note that the .groups="drop" is just to avoid a message printing, but in this case you can omit it if you prefer.

tanglef
  • 106
  • 1
  • 4