gpt4 book ai didi

r - 为什么 dplyr::cummean(x) 不等于 cumsum(x)/seq_along(x)?

转载 作者:行者123 更新时间:2023-12-03 23:46:35 24 4
gpt4 key购买 nike

为什么 cummean(x) 不等于 cumsum(x)/seq_along(x)

set.seed(456)
x <- as.integer(runif(30)*300)
x

cummean(x)
cumsum(x)/seq_along(x)

[1] 26 63 219 255 236 99 24 85 71 115 111 65 226 246 179 195 252 135 215 87 53 216 271 133 251 211 285 192 22 76
[1] 26.00000 26.00000 38.33333 83.50000 117.80000 137.50000 132.00000 118.50000 114.77778 110.40000 110.81818 110.83333 107.30769 115.78571 124.46667 127.87500 131.82353
[18] 138.50000 138.31579 142.15000 139.52381 135.59091 139.08696 144.58333 144.12000 148.23077 150.55556 155.35714 156.62069 152.13333

[1] 26.0000 44.5000 102.6667 140.7500 159.8000 149.6667 131.7143 125.8750 119.7778 119.3000 118.5455 114.0833 122.6923 131.5000 134.6667 138.4375 145.1176 144.5556 148.2632
[20] 145.2000 140.8095 144.2273 149.7391 149.0417 153.1200 155.3462 160.1481 161.2857 156.4828 153.8000

最佳答案

dplyr::cummean 1.1.0 开始,这实际上是 dplyr 函数的一个问题,请参阅 here 。 Romain Francois 四天前推送了一个修复程序,所以如果你从 github 中提取 dplyr 版本,它应该会给出正确的结果,将在几秒钟内尝试更新。

在上述问题中使用的示例:

library(tidyverse)
x <- 1:5

# long(er) way
cumsum(x) / seq_along(x)
#> [1] 1.0 1.5 2.0 2.5 3.0

# dplyr 0.8.5 cummean()
cummean(x)
#> [1] 1.0 1.5 2.0 2.5 3.0

# dplyr 1.0.0 cummean()
cummean(x)
#> [1] 1.000000 1.000000 1.333333 1.750000 2.200000

导致该错误的原因(也来自上面链接的 github 问题):

It looks like the indexing is off by one for dplyr_cummean in /src/funs.cpp, causing the first index to be repeated twice (and the last index to be dropped). I'll submit a pull request with a slight change which I think makes it work as intended.



更新:
github (1.0.0.9000) 上的当前版本给出了正确的结果:
library(dplyr)
packageVersion("dplyr")
#[1] ‘1.0.0.9000’

set.seed(456)
x <- as.integer(runif(30)*300)

all(dplyr::cummean(x) == cumsum(x)/seq_along(x))
#[1] TRUE

关于r - 为什么 dplyr::cummean(x) 不等于 cumsum(x)/seq_along(x)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62356825/

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