我有一张桌子,我需要填充平均值.我目前正在使用低效的代码,这将花费很长时间在大型数据集上.例:
样本数据:
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)
Run Code Online (Sandbox Code Playgroud)
码:
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 …Run Code Online (Sandbox Code Playgroud)