【问题标题】:na.approx only when less than 3 consecutive NA in a columnna.approx 仅当列中的连续 NA 少于 3 个时
【发布时间】:2021-07-23 01:48:45
【问题描述】:
mydata <-data.frame(group = c(1,1,1,1,1,2,2,2,2,2), score = c(10, NA, NA, 20, 30, 5, NA, NA, NA, 40)) 

当“值”中最接近的非 NA 条目之间的连续 NA 少于 3 个时,我正在尝试使用 dplyr 使用 na.approx 插入“x”,从“mydata”。插值后的 x 值存储在“x_approx”中。

如果没有“值”中连续 NA 数量的条件,我使用以下代码:

library(zoo)
mydata %>%
     group_by(group) %>%
     mutate(score_approx = na.approx(score)) %>%
     mutate(score_approx = coalesce(score_approx,score))

mydata
# A tibble: 10 x 3
# Groups:   group [2]
   group score score_approx
   <dbl> <dbl>        <dbl>
 1     1    10         10  
 2     1    NA         13.3
 3     1    NA         16.7
 4     1    20         20  
 5     1    30         30  
 6     2     5          5  
 7     2    NA         13.8
 8     2    NA         22.5
 9     2    NA         31.2
10     2    40         40

但是,所需的数据框是:

# A tibble: 10 x 3
# Groups:   group [2]
   group score score_approx
   <dbl> <dbl>        <dbl>
 1     1    10         10  
 2     1    NA         13.3
 3     1    NA         16.7
 4     1    20         20  
 5     1    30         30  
 6     2     5          5  
 7     2    NA         NA
 8     2    NA         NA
 9     2    NA         NA
10     2    40         40

【问题讨论】:

    标签: r dplyr zoo


    【解决方案1】:

    您可以在na.approx 中使用maxgap 参数-

    library(dplyr)
    library(zoo)
    
    mydata %>%
      group_by(group) %>%
      mutate(score_approx = na.approx(score, maxgap = 2)) %>%
      ungroup
    
    #   group score score_approx
    #   <dbl> <dbl>        <dbl>
    # 1     1    10         10  
    # 2     1    NA         13.3
    # 3     1    NA         16.7
    # 4     1    20         20  
    # 5     1    30         30  
    # 6     2     5          5  
    # 7     2    NA         NA  
    # 8     2    NA         NA  
    # 9     2    NA         NA  
    #10     2    40         40  
    

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      • 2021-05-08
      相关资源
      最近更新 更多