按组填充缺失值,但不要结转

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

我有下表:

身份证 日期 补偿
004 一月 1 不适用
004 一月 2 日 55
004 1 月 6 日 不适用
010 12月12日 不适用
010 12月14日 不适用
010 12月15日 66
010 12月16日 不适用
012 2月5日 33
012 2 月 9 日 不适用
012 2月10日 不适用
012 5月2日 89

我基本上想要的是填写组内缺失的值,然后将值转移到下一组。这是我的代码

DataWanted <- Data
        dplyr::group_by("ID", "Date") %>% 
fill("Compensation", .direction = "down")

请参阅表格,了解我得到的补偿结果与我实际想要的补偿结果。基本上我想通过分组 ID 来填充值。因此,如果一开始没有对某个组进行补偿,那么我不想复制之前 ID 中的补偿值,只需将其保留为 NA 即可。

身份证 日期 补偿栏获取 我要的报酬栏
004 一月 1 不适用 不适用
004 一月 2 日 55 55
004 1 月 6 日 55 55
010 12 月 12 日 55 不适用
010 12月14日 55 不适用
010 12月15日 66 66
010 12月16日 66 66
012 2月5日 33 33
012 2 月 9 日 33 33
012 2月10日 33 33
012 5月2日 89 89
r tidyr
1个回答
0
投票
library(tidyverse)

data <- tribble(~ID, ~Date, ~Compensation,
"004",  "Jan1",     NA,
"004",  "Jan2",     55,
"004",  "Jan6",     NA,
"010",  "Dec12",    NA,
"010",  "Dec14",    NA,
"010",  "Dec15",    66,
"010",  "Dec16",    NA,
"012",  "Feb5",     33,
"012",  "Feb9",     NA,
"012",  "Feb10",    NA,
"012",  "May2",     89)

data |>    
  mutate(Date = Date |> 
           str_replace("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)", " ") |> 
           paste(" 2023") |> 
           mdy()) |> 
  arrange(Date) |> 
  group_by(ID) |>    
  fill(Compensation, .direction = "down") |> 
  ungroup()

# A tibble: 11 × 3
   ID    Date       Compensation
   <chr> <date>            <dbl>
 1 004   2023-01-01           NA
 2 004   2023-01-02           55
 3 004   2023-01-06           55
 4 012   2023-02-05           33
 5 012   2023-02-09           33
 6 012   2023-02-10           33
 7 012   2023-05-02           89
 8 010   2023-12-12           NA
 9 010   2023-12-14           NA
10 010   2023-12-15           66
11 010   2023-12-16           66

我不确定为什么将

.direction
参数设置为 down 不起作用。我无法复制您的问题,或者也许我只是不理解其意图。

© www.soinside.com 2019 - 2024. All rights reserved.