仅当一个零且周围值大于零时才插入零值

问题描述 投票:0回答:1

我想在时间序列数据帧中插入零值,但前提是:1)只有一个缺失值,因此后续和后续值均非零,2)周围的非零值高于 2。

参见下面的示例。非常感谢!

df = data.frame(row.names = c("第 1 年", "第 2 年", "第 3 年", "第 4 年", "第 5 年"), 人物1 = c(33,0,8,6,3),人物2 = c(1,3,0,0,5),人物3 = c(0,3,0,5,1))

之前:

       person1 person2 person3
year 1      33       1       0
year 2       0       3       3
year 3       8       0       0
year 4       6       0       2
year 5       3       5       1

想要的结果:

       person1 person2 person3
year 1      33       1       0
year 2     *20.5*    3       3
year 3       8       0       0
year 4       6       0       2
year 5       3       5       1

我尝试了领先和滞后突变以及 na.approx 函数的不同变体,但无济于事。

r dplyr interpolation missing-data imputation
1个回答
1
投票

这是使用 tidyverse 的一句台词:

library(tidyverse)

df <- data.frame(row.names = c("year 1", "year 2", "year 3", "year 4", "year 5"), person1 = c(33,0,8,6,3), person2 = c(1,3,0,0,5), person3 = c(0,3,0,5,1))

df |> 
  mutate(
    across(everything(), \(x) ifelse(x == 0 & lag(x, default = 0) > 2 & lead(x, default = 0) > 2, rowMeans(cbind(lag(x), lead(x))), x))
  )
  
       person1 person2 person3
year 1    33.0       1       0
year 2    20.5       3       3
year 3     8.0       0       4
year 4     6.0       0       5
year 5     3.0       5       1
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.