# 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 <- data.frame(read_delim("~/...", ";", escape_double = FALSE, trim_ws = TRUE))
# Visualize head of the 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 <-- 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)
A;AB;1
B;AB;2
C;AB;3
B;AB;4
B;AB;5

dfr %>% group_by(id, attribute) %>% summarize(mean=mean(time))


Result

# A tibble: 3 x 3
# Groups:   id [?]
id attribute  mean
<fctr>    <fctr> <dbl>
1      A        AB 3.500
2      B        AB 3.667
3      C        AB 3.000


What your trying to do is call a group-by you want to group by the id column and the find the mean of column time in each group. I suggest you look into the aggregate function. This function does the following: Splits the data into subsets, computes summary statistics for each, and returns the result in a convenient form.

aggregate( time~ id, FUN=mean, data=yourdataframe)