平均每个点
DPUT数据
df <- structure(list(Log_Score = c(1.02036009176836, 1.04731899428056,
1.26147129638715, 2.01321383095142, 1.21566884408913, 1.04241773032447
), Time_Stamp = 1:6, Time_Log_Mean = c(0, 0, 0, 0, 0, 0)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
> df
# A tibble: 6 x 3
Log_Score Time_Stamp Time_Log_Mean
<dbl> <int> <dbl>
1 1.02 1 0
2 1.05 2 0
3 1.26 3 0
4 2.01 4 0
5 1.22 5 0
6 1.04 6 0
我正在尝试使用for for循环创建每个时间点的平均值,但似乎无法使其正常工作。我使用的代码是:
for (i in 1:nrow(df)) {
df$Time_Log_Mean[i] <- ((sum(df$Log_Score[1:i]))/(df$Time_Stamp[i]))
}
该代码在初次给我错误消息后神秘地开始工作:
分配的数据值必须与现有数据兼容。 x存在 数据有335行。 X分配的数据有6553行。我只有 尺寸1被回收。
Dput data
df <- structure(list(Log_Score = c(1.02036009176836, 1.04731899428056,
1.26147129638715, 2.01321383095142, 1.21566884408913, 1.04241773032447
), Time_Stamp = 1:6, Time_Log_Mean = c(0, 0, 0, 0, 0, 0)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
> df
# A tibble: 6 x 3
Log_Score Time_Stamp Time_Log_Mean
<dbl> <int> <dbl>
1 1.02 1 0
2 1.05 2 0
3 1.26 3 0
4 2.01 4 0
5 1.22 5 0
6 1.04 6 0
I am trying to create a mean average for every point in time using a for loop but can't seem to get it to work. The code I was using is:
for (i in 1:nrow(df)) {
df$Time_Log_Mean[i] <- ((sum(df$Log_Score[1:i]))/(df$Time_Stamp[i]))
}
The code has mysteriously started to work after initial giving me the error message:
Assigned data value must be compatible with existing data. x Existing
data has 335 rows. x Assigned data has 6553 rows. i Only vectors of
size 1 are recycled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来像是
由 reprex package (v2.0.1.1(v2.0.1.1(v2.0.1), )
looks like a cumulative average calculation
Created on 2022-04-25 by the reprex package (v2.0.1)