如何将非零值分配给前零个值

时间:2020-09-17 18:26:16

标签: r assign

我在R中有关于人的发票和付款的信息:

dt <- data.frame(Date = seq.Date(as.Date("2020-01-01"), by = "month", length.out = 9),
                 Invoice = c(9, 9, 9, 10, 10, 10, 10, 10, 10),
                 Payment = c(0, 9, 9, 0, 0, 25, 10, 13, 20))

如您所见,有几个月,Payment = 0。我想将非零付款分配给过去的零付款,如下所示:

   Invoice_date Invoice_amount Payment_date Payment_amount
1    2020-01-01              9   2020-02-01              9 (The 2nd month payment assigned to 1st month)
2    2020-02-01              9   2020-03-01              9 (The 3rd month payment assigned to 2nd month)
3    2020-03-01              9   2020-06-01              9 (original payment - 25, the 6th month payment assigned to 3rd month)
4    2020-04-01             10   2020-06-01             10 (original payment - 25, the 6th month payment assigned to 4th month)
5    2020-05-01             10   2020-06-01              6 (original payment - 25, the 6th month payment assigned to 5th month)
6    2020-05-01             10   2020-07-01             10
7    2020-06-01             10   2020-08-01             10 (original payment - 13)
8    2020-07-01             10   2020-08-01              3 (original payment - 13)
9    2020-07-01             10   2020-09-01              7 (original payment - 20)
10   2020-08-01             10   2020-09-01             10 (original payment - 20)
11   2020-09-01             10   2020-09-01              3 (original payment - 20)

也许您知道做到这一点的最佳方法?

1 个答案:

答案 0 :(得分:0)

如果您有先前的0值需要用第一个非零值覆盖,那么这里是一个建议:

dt$Payment2 <- ifelse(dt$Payment == 0, NA_real_, dt$Payment)
dt$Payment2 <- zoo::na.locf(dt$Payment2, fromLast = TRUE)
dt
#         Date Invoice Payment Payment2
# 1 2020-01-01       9       0        9
# 2 2020-02-01       9       9        9
# 3 2020-03-01       9       9        9
# 4 2020-04-01      10       0       25
# 5 2020-05-01      10       0       25
# 6 2020-06-01      10      25       25
# 7 2020-07-01      10      10       10
# 8 2020-08-01      10      13       13
# 9 2020-09-01      10      20       20

在tidyverse说中,这是

library(dplyr)
dt %>%
  mutate
    Payment2 = if_else(Payment == 0, NA_real_, Payment),
    Payment2 = zoo::na.locf(Payment2, fromLast = TRUE)
  )