0

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
Community
  • 1
  • 1
Chaturvedi Dewashish
  • 1,469
  • 2
  • 15
  • 39
  • 2
    Because the dates are in reverse order, you'll need to adjust for that as `which(L)[rev(cumsum(L))]`. If you don't understand Grothendieck's solution, grab a good introductory book on `R`. – Khashaa Jan 12 '15 at 06:15
  • `z[] <- coredata(z)[which(L)[cumsum(rev(L))],]` to be exact. – Khashaa Jan 12 '15 at 06:23

1 Answers1

1

It seems you are struggling with zero entries. Why not use NA? If my assumption is correct, na.locf is the function you need.

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.

tonytonov
  • 25,060
  • 16
  • 82
  • 98