gpt4 book ai didi

r - r 中一列中最近邻值的平均值

转载 作者:行者123 更新时间:2023-12-01 23:48:26 24 4
gpt4 key购买 nike

我这里有一个数据框:

df <- data.frame("Time" = 1:10, "Value" = c(1.7,NA,-999,-999,1.5,1.6,NA,4,-999,8))

“NA”表示没有观察,就把它们留在那里。 “-999”表示观测值被识别为异常值。

enter image description here

现在我试图用最近值的平均值替换“-999”。例如:

The first "-999" should be replaced with (1.7+1.5)/2 = 1.6
The second "-999" should be replaced with (1.7+1.5)/2 = 1.6
The last "-999" should be replaced with (4.0+8.0)/2 = 6

我尝试使用next 语句来查找下一次迭代,并使用if 语句来决定在哪里停止。但是我怎样才能去检查以前的迭代呢?或者是否有另一种解决方案?

非常感谢。

最佳答案

利用 dplyrpurrrtidyr 的一种方法可能是:

df %>%
mutate(New_Value = if_else(Value == -999,
map_dbl(.x = seq_along(Value),
~ mean(c(tail(na.omit(na_if(Value[1:(.x - 1)], -999)), 1),
head(na.omit(na_if(Value[(.x + 1):n()], -999)), 1)))),
Value))

Time Value New_Value
1 1 1.7 1.7
2 2 NA NA
3 3 -999.0 1.6
4 4 -999.0 1.6
5 5 1.5 1.5
6 6 1.7 1.7
7 7 NA NA
8 8 4.0 4.0
9 9 -999.0 6.0
10 10 8.0 8.0

关于r - r 中一列中最近邻值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63812851/

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