运行以下代码后:
using: Data.table library:
library(data.table) # CRAN version 1.10.4 used
setDT(bb)[, D := bal / shift(bal, 6L)][seq(1L, nrow(bb), 5L), D := NA][]
OR
Using: Dplyr library:
DF %>%
group_by(g1=seq_along(bal) %% 5) %>%
mutate(denominator=lag(bal)) %>%
ungroup() %>%
group_by(g2=(seq_along(bal) - 1) %/% 5) %>%
mutate(denominator=lag(denominator),
D=bal / denominator) %>%
ungroup()
我得到以下输出:
date Bucket balance D
1/31/2013 bkt 0 10 NA
1/31/2013 bkt 1(10-20) 11 NA
1/31/2013 bkt 2(20-30) 12 NA
1/31/2013 bkt 3(30-40) 13 NA
1/31/2013 bkt 4(40+) 14 NA
2/28/2013 bkt 0 20 NA
2/28/2013 bkt 1(10-20) 30 3.00
2/28/2013 bkt 2(20-30) 40 3.63
2/28/2013 bkt 3(30-40) 50 4.16
2/28/2013 bkt 4(40+) 60 4.61
3/30/2013 bkt 0 10 NA
3/30/2013 bkt 1(10-20) 11 0.55
3/30/2013 bkt 2(20-30) 12 0.40
3/30/2013 bkt 3(30-40) 13 0.32
3/30/2013 bkt 4(40+) 15 0.30
现在的问题是:在Bucket专栏中每隔bkt 3和bkt 4,我需要在coloumn D打印100.
预期产量: 在每个bkt 3和bkt 4,它应该在coloumn D中打印100.
date Bucket balance D
1/31/2013 bkt 0 10 NA
1/31/2013 bkt 1(10-20) 11 NA
1/31/2013 bkt 2(20-30) 12 NA
1/31/2013 bkt 3(30-40) 13 NA
1/31/2013 bkt 4(40+) 14 NA
2/28/2013 bkt 0 20 NA
2/28/2013 bkt 1(10-20) 30 3.00
2/28/2013 bkt 2(20-30) 40 3.63
2/28/2013 bkt 3(30-40) 50 100
2/28/2013 bkt 4(40+) 60 100
3/30/2013 bkt 0 10 NA
3/30/2013 bkt 1(10-20) 11 0.55
3/30/2013 bkt 2(20-30) 12 0.40
3/30/2013 bkt 3(30-40) 13 100
3/30/2013 bkt 4(40+) 15 100
Also tried:
setDT(bb1)[Bucket == "bkt 3(30-40)" , D := 100 ]
输出 - 没有错误,也没有要打印的值。
请提前帮助,谢谢。