[英]Using last observation for zero in time series R
I am taking input as 我正在输入
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
And output am trying to get is 而输出试图获得的是
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
according to this question I am trying to get output but result is not as per requirement 根据这个问题,我试图获得输出,但结果不符合要求
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
It seems you are struggling with zero entries. 看来您正在为零条目而苦苦挣扎。 Why not use NA
? 为什么不使用NA
? If my assumption is correct, na.locf
is the function you need. 如果我的假设正确, 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
If you really need 0
instead of NA
, substitute it back after na.locf
. 如果确实需要0
而不是NA
,则将其替换为na.locf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.