0

i want to calculate the mean values based on the id out of a data frame like this:

id  |  value
1      100
2      200
3      100
1      100
1      100
3      200
2      300

that's what i've coded so far:

ids <- unique(df$id)
for(i in ids){
  ...
}

how am i able to call only the values with each id to calculate the mean?

outcome (mean) of the example values above should be: 1 = 100, 2 = 250, 3 = 150

Kev Schl
  • 3
  • 3

2 Answers2

0

You can use tapply:

tapply(df$value, df$id, mean)
neves
  • 796
  • 2
  • 10
  • 36
0

You can group by the ID column and then easily calculate a mean or any other aggregate metric:

library(tidyverse)
df_summary <- df %>%
  group_by(id) %>%
  summarise(id_mean = mean(value))
alex_jwb90
  • 1,663
  • 1
  • 11
  • 20