Combining results via arithmetic mean For combining the results of different measurements, I want to calculate their arithmetic mean. Imagine the following dataset:

id;attribute;time
A;AB;1
B;AB;2
C;AB;3
B;AB;4
B;AB;5
A;AB;6


I want to combine all results with id A and get their mean. The expected dataset looks like the followind. Be aware, that the value of the in between attribute, is not important, I've chosen the first entry.

id attribute     time
A  AB            3.500000
B  AB            3.666667
C  AB            3.000000


The code below does the right thing, but I'm wondering if there is a better solution for this kind of problem.

# Read in the data
data &lt;- data.frame(read_delim("~/...", ";", escape_double = FALSE, trim_ws = TRUE))
# Visualize head of the data
head(data)    

# Define function to calculate the mean
calculate_mean = function(data){

  # Prepare empty result data set
  result = data.frame(id=character(), 
                      attribute=character(),
                      time=integer())

  # Iterate over specified id &lt;-- Change this one to the one you want to iterate over
  iterator = unique(data$id)

  # Fill result dataset with mean
  for(i in iterator){
    subset = subset(data, data$id == i)
    arithmetic_mean = mean(subset$time)
    result = rbind(result, data.frame(subset[1,]$id, 
                                      subset[1,]$attribute, 
                                      arithmetic_mean))
  }

  # Set colnames properly
  colnames(result) = colnames(data)

  return(result)
}    

# Call function
result = calculate_mean(data)    

# Display the result
result


Do you have an idea? Thanks for your support.
Try it the R tidyverse way:

library(dplyr)
dfr &lt;- read.table(text = "id;attribute;time
A;AB;1
B;AB;2
C;AB;3
B;AB;4
B;AB;5
A;AB;6", header=TRUE, sep=";")

dfr %&gt;% group_by(id, attribute) %&gt;% summarize(mean=mean(time))


Result

# A tibble: 3 x 3
# Groups:   id [?]
      id attribute  mean
  &lt;fctr&gt;    &lt;fctr&gt; &lt;dbl&gt;
1      A        AB 3.500
2      B        AB 3.667
3      C        AB 3.000