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
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 <-- 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.