将 R 中 mutate 和 rollapply 中的第一个计算替换为 0

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

我在 R 中有一个名为 Data 的数据框。

library(tibble)
library(dplyr)
library(zoo)
Data <- tibble(
  var = c("A", "A", "A", "A", "A","A"),
  val = c(1, 1, 1, 1, 1.5 , 1.5)
)%>%
  mutate( roll_sd   = rollapplyr(val, width = seq_len(n()), FUN = function(x) sd(x, na.rm = TRUE), fill = NA))
Data

带输出:

# A tibble: 6 × 3
  var     val roll_sd
  <chr> <dbl>   <dbl>
1 A       1    NA    
2 A       1     0    
3 A       1     0    
4 A       1     0    
5 A       1.5   0.224
6 A       1.5   0.258

我希望除0之外的第一个roll_sd再次为0,然后按照最初计算的方式继续。我怎样才能在 R 中做到这一点?

理想的输出是这样的:

# A tibble: 6 × 3
  var     val roll_sd
  <chr> <dbl>   <dbl>
1 A       1    NA    
2 A       1     0    
3 A       1     0    
4 A       1     0    
5 A       1.5   0
6 A       1.5   0.258
r zoo rollapply
1个回答
0
投票

根据您对我的评论的回答,我相信这样的东西可能对您有用:

library(tibble)
library(dplyr)
library(zoo)

Data <- tibble(
  var = c("A", "A", "A", "A", "A","A"),
  val = c(1, 1, 1, 1, 1.5 , 1.5)
)%>%
  mutate( roll_sd   = rollapplyr(val, width = seq_len(n()), 
                                 FUN = function(x) sd(x, na.rm = TRUE), 
                                 fill = NA))

Data <- rbind(Data, Data) # added so there are 2 places to be set to 0

to_zero <- which(!is.na(Data$roll_sd) & Data$roll_sd > 0) # find all non-0 and non-NA numbers
non_consecutive <- to_zero[c(TRUE, diff(to_zero) > 1)] # get every non-0 number
Data$roll_sd[non_consecutive] <- 0 # set to 0

> Data

# A tibble: 12 × 3
   var     val roll_sd
   <chr> <dbl>   <dbl>
 1 A       1    NA    
 2 A       1     0    
 3 A       1     0    
 4 A       1     0    
 5 A       1.5   0    
 6 A       1.5   0.258
 7 A       1    NA    
 8 A       1     0    
 9 A       1     0    
10 A       1     0    
11 A       1.5   0    
12 A       1.5   0.258
© www.soinside.com 2019 - 2024. All rights reserved.