【发布时间】:2014-02-11 12:29:23
【问题描述】:
我有一张需要用平均值填充的表格。我目前正在使用效率低下的代码,这将在大型数据集上花费很长时间。示例:
样本数据:
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)
代码:
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
我希望能够使用高效的代码从输入到输出。我是 R 新手,非常感谢您的帮助!
【问题讨论】:
-
您能解释一下为什么您觉得它效率低下,以及您为提高效率所做的努力吗?
-
关于提高工作代码效率的问题可能更适合 Code Review (codereview.stackexchange.com)
标签: r statistics aggregate data.table mean