有效填充R中的均值和值
我有一个表,我需要填充平均值。我目前使用的代码效率低下,在大型数据集上需要很长时间。例如: 样本数据:有效填充R中的均值和值,r,statistics,aggregate,data.table,mean,R,Statistics,Aggregate,Data.table,Mean,我有一个表,我需要填充平均值。我目前使用的代码效率低下,在大型数据集上需要很长时间。例如: 样本数据: 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,
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
代码:
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
y功能将在x
和y
中具有相同名称的列上匹配merge
(a
和b
):
您正在查找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
x数据。表格
是方法:
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)
x、 dt您能解释一下为什么您觉得它效率低下,以及您是如何使它更高效的吗?关于提高工作代码效率的问题可能更适合于代码审查()