【问题标题】:Why isn't the mean() function in R giving me the right result?为什么 R 中的 mean() 函数没有给我正确的结果?
【发布时间】:2020-08-10 14:52:33
【问题描述】:

我一直在练习 R (3.6.3) 的基础知识,但我已经花了好几个小时试图理解这个问题。这是练习:

第一步:生成1到3之间总长度为100的数据序列; #使用 jitter 函数(有一个很大的因素)给你的数据添加噪声 第 2 步:计算滚动平均值的向量 roll.mean 与 5 个连续点的平均值。这个向量只有 96 个平均值。 第 3 步:将这些平均值的向量添加到绘图中 第 4 步:通过使用参数 consec (default=5) 和 y 制作函数来概括第 2 步和第 3 步。

y88 = seq(1,3,0.02)
y = jitter(y88, 120, set.seed(1))
y = y[-99] # removed one guy so y can have 100 elements, as asked

roll.meanT = rep(0,96)
for (i in 1:length(roll.meanT)) # my 'reference i' is roll.mean[i], not y[i]
{
roll.meanT[i] = (y[i+4]+y[i+3]+y[i+2]+y[i+1]+y[i])/5  
}

plot(y)
lines(roll.meanT, col=3, lwd=2)

这产生了这个情节:

然后,我继续使用一个函数进行概括(它要求我概括步骤 2 和 3,因此忽略了数据创建步骤)并且我认为 y 保持不变):

fun50 = function(consec=5,y)
{
  roll.mean <- rep(NA,96) # Apparently, we just leave NA's as NA's, since lenght(y) is always greater than lenght(roll.means)
  for (i in 1:96)
  {
    roll.mean[i] <- mean(y[i:i+consec-1]) # Using mean(), I'm able to generalize.
  } 
  plot(y)
  lines(roll.mean, col=3, lwd=2)
}

这给了我一个完全不同的情节:

当我手动尝试查看 mean(y[1:5]) 是否产生正确的均值时,确实如此。我知道我本可以在第一部分中使用 mean() 函数,但我真的很想使用 (y[i+4]+y[i+3]+y[i+2]+ y[i+1]+y[i])/5 或 mean(y[1:5],......)。

【问题讨论】:

    标签: r


    【解决方案1】:

    你有电话

        roll.mean[i] <- mean(y[i:i+consec-1]) # Using mean(), I'm able to generalize.
    

    我相信您的意图是获取索引 i 到 (i+consec-1) 的值。不幸的是,: 运算符优先于算术运算。

    > 1:1+5-1  #(this is what your code would do for i=1, consec=5)
    [1] 5
    > (1:1)+5-1 # this is what it's actually doing for you
    > 5
    > 2:2+5-1 #(this is what your code would do for i=2, consec=5)
    [1] 6
    > 3:3+5-1 #(this is what your code would do for i=3, consec=5)
    [1] 7
    > 3:(3+5-1) #(this is what you want your code to do for i=3, consec=5)
    [1] 3 4 5 6 7
    

    所以要修复 - 只需添加一些括号

    roll.mean[i] <- mean(y[i:(i+consec-1)]) # Using mean(), I'm able to generalize.
    

    【讨论】:

    • 需要注意的一点 - 您可能会考虑查看之前的值,而不是当前观察之前的值。通常情况下,诸如滚动平均值之类的东西用于平滑时间序列类型的事物,考虑未来的观察结果来平滑当前值并不一定“公平”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2016-03-31
    • 1970-01-01
    • 2011-10-22
    相关资源
    最近更新 更多