0
$\begingroup$

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.

$\endgroup$

3 Answers 3

2
$\begingroup$

Try it the R tidyverse way:

library(dplyr)
dfr <- 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 %>% 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
$\endgroup$
1
$\begingroup$

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.

$\endgroup$
0
$\begingroup$
aggregate( time~ id, FUN=mean, data=yourdataframe)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.