當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R dbplyr fill.tbl_lazy 用上一個或下一個值填充缺失值


用上一個或下一個值填充缺失值

用法

# S3 method for tbl_lazy
fill(.data, ..., .direction = c("down", "up", "updown", "downup"))

參數

.data

由數據庫查詢支持的惰性 DataFrame 。

...

要填充的列。

.direction

填充缺失值的方向。目前是"down"(默認)或"up"。請注意,當 .data 按非數字列排序時,"up" 不起作用。作為解決方法,請提前自行恢複訂單;例如,將 arrange(x, desc(y)) 替換為 arrange(desc(x), y)

例子

squirrels <- tibble::tribble(
  ~group,    ~name,     ~role,     ~n_squirrels, ~ n_squirrels2,
  1,      "Sam",    "Observer",   NA,                 1,
  1,     "Mara", "Scorekeeper",    8,                NA,
  1,    "Jesse",    "Observer",   NA,                NA,
  1,      "Tom",    "Observer",   NA,                 4,
  2,     "Mike",    "Observer",   NA,                NA,
  2,  "Rachael",    "Observer",   NA,                 6,
  2,  "Sydekea", "Scorekeeper",   14,                NA,
  2, "Gabriela",    "Observer",   NA,                NA,
  3,  "Derrick",    "Observer",   NA,                NA,
  3,     "Kara", "Scorekeeper",    9,                 10,
  3,    "Emily",    "Observer",   NA,                NA,
  3, "Danielle",    "Observer",   NA,                NA
)
squirrels$id <- 1:12

tbl_memdb(squirrels) %>%
  window_order(id) %>%
  tidyr::fill(
    n_squirrels,
    n_squirrels2,
  )
#> # Source:     SQL [?? x 6]
#> # Database:   sqlite 3.41.2 [:memory:]
#> # Ordered by: id
#>    group name     role        n_squirrels n_squirrels2    id
#>    <dbl> <chr>    <chr>             <dbl>        <dbl> <int>
#>  1     1 Sam      Observer             NA            1     1
#>  2     1 Mara     Scorekeeper           8            1     2
#>  3     1 Jesse    Observer              8            1     3
#>  4     1 Tom      Observer              8            4     4
#>  5     2 Mike     Observer              8            4     5
#>  6     2 Rachael  Observer              8            6     6
#>  7     2 Sydekea  Scorekeeper          14            6     7
#>  8     2 Gabriela Observer             14            6     8
#>  9     3 Derrick  Observer             14            6     9
#> 10     3 Kara     Scorekeeper           9           10    10
#> # ℹ more rows
源代碼:R/verb-fill.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Fill in missing values with previous or next value。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。