Effectively fill averages in R

I have a table that I need to populate with an average value. I am currently using inefficient code that will take a lot of time on large datasets. Example:

Data examples

x = read.table(text="a b value mean
                     1 1 10 0
                     1 1 12 0
                     2 2 14 0
                     2 1 16 0", header=TRUE)

Code:

y <- aggregate(x$value, list(a = x$a,b = x$b), mean)
print(y)
#   a b  x
# 1 1 1 11
# 2 2 1 16
# 3 2 2 14

for (i in 1:4) {
  for (j in 1:3) {
    if (x$a[i]==y$a[j] && x$b[i]==y$b[j]) {
      x$mean[i]=y$x[j] }
  }
}
print(x) # This is the final output
#   a b value mean
# 1 1 1    10   11
# 2 1 1    12   11
# 3 2 2    14   14
# 4 2 1    16   16

I want to be able to get effective code from input to output. I am new to R, so many thanks for the help!

+4
source share
3 answers

data.table - way:

library(data.table)
x.dt <- data.table(x[1:3])               # convert first three cols
x.dt[, mean:=mean(value), by=list(a, b)] # add back mean
#    a b value mean
# 1: 1 1    10   11
# 2: 1 1    12   11
# 3: 2 2    14   14
# 4: 2 1    16   16

data.table very fast.

+7
source

You are looking for ave:

x <- transform(x, mean = ave(value, a, b, mean))

#   a b value mean
# 1 1 1    10   11
# 2 1 1    12   11
# 3 2 2    14   14
# 4 2 1    16   16
+5
source

The function mergewill correspond to columns with the same name in xand y( aand b):

x = data.frame(a=c(1, 1, 2, 2), b=c(1, 1, 2, 1), value=c(10, 12, 14, 16))
y = aggregate(x$value, list(a=x$a, b=x$b), mean)
merge(x, y, sort=F)
#   a b value  x
# 1 1 1    10 11
# 2 1 1    12 11
# 3 2 2    14 14
# 4 2 1    16 16
+3
source

All Articles