gpt4 book ai didi

r - n行的平均值

转载 作者:行者123 更新时间:2023-12-04 12:14:57 26 4
gpt4 key购买 nike

我有一个包含三列的数据框:IdDateValue,并希望按平均降采样:获取下20行,从这20行中构建Value的平均值,并将其添加到具有相同结构的新数据框中。 Date应该是20行的第一个值。

我以这种方式尝试过(可能太糟糕了:):

resample.downsample <- function(data, by=20)
{
i <- 0
nmax <- nrow(data)
means <- c()
while(i < nmax)
{
means <- c(means, mean(subset(data, Id > i & Id <= i+by)$Value))
i <- i+by
}
return (
data.frame(
Id = seq(1, length.out=(nmax/by), by=1),
Date = seq(startDate, length.out=(nmax/by), by=(1/by)),
Value = means
)
)
}

这适用于小型数据集,但可以在我的真实数据集(〜4000000行)上永久运行。任何想法如何优化此功能?

样本数据(输入,输出应具有相同的结构,类:整数,数字,POSIXct/POSIXt):
    Value   Id  Date
1 125 1 2011-06-30 22:41:50
2 127 2 2011-06-30 22:41:50
3 126 3 2011-06-30 22:41:50
4 123 4 2011-06-30 22:41:50
5 130 5 2011-06-30 22:41:50
6 131 6 2011-06-30 22:41:50
7 128 7 2011-06-30 22:41:50

最佳答案

请参阅此答案以获取适合您的方法。 How to get the sum of each four rows of a matrix in R。在您的情况下,它将是:

colMeans(matrix(data$Value, nrow=20))

您当前的获取第一个Date的方法应该可以。

关于r - n行的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6903747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com