我正在接受输入
Quant1 Quant2
2013-01-23 400 200
2013-01-22 0 0
2013-01-21 0 0
2013-01-20 125 100
2013-01-18 120 0
输出我试图得到的是
Quant1 Quant2
2013-01-23 400 200
2013-01-22 125 100
2013-01-21 125 100
2013-01-20 125 100
2013-01-18 120 0
根据this question我试图获得输出但结果不符合要求
z <- structure(c(400L, 0L, 0L, 125L, 120L, 200L, 0L, 0L, 100L,
0L), .Dim = c(5L, 2L), .Dimnames = list(NULL, c("Quant1", "Quant2"
)), index = structure(c(15728, 15727, 15726, 15725, 15723), class = "Date"),
class = "zoo")
L <- rowSums(z != 0) > 0
z[] <- coredata(z)[which(L)[cumsum(L)],]
z
Quant1 Quant2
2013-01-23 400 200
2013-01-22 0 0
2013-01-21 0 0
2013-01-20 0 0
2013-01-18 120 0
答案 0 :(得分:1)
看来你正在努力应对零条目。为什么不使用NA
?如果我的假设是正确的,na.locf
就是你需要的功能。
coredata(z)[coredata(z) == 0] <- NA
na.locf(z, fromLast = T)
Quant1 Quant2
2013-01-18 120 NA
2013-01-20 125 100
2013-01-21 125 100
2013-01-22 125 100
2013-01-23 400 200
如果您确实需要0
而不是NA
,请在na.locf
后替换它。