我有一張我需要用平均值填充的表格。我目前正在使用效率低下的代碼,這將在大型數據集上花費很長時間。例如:在R中有效填充平均值旁邊的值
樣本數據:
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新手,非常感謝您的幫助!
你能解釋爲什麼你覺得它效率低下,你試圖讓它更高效嗎? – dethtron5000
有關提高工作代碼效率的問題可能更適合於代碼審查(http://codereview.stackexchange.com/) –