Hi, I need some help improving this ugly code I wrote. I would like to shift forward a zoo object, matrix, ts, or list by "shift" items (default 1) and fill the holes with 0's.
The code below works, but it looks ugly. I could write a function lag.zerofill() which calls the two functions below depending on the class() of the item passed in, but that feels very unlike R. What is the proper way to write this code so that it works for all input types? Is a switch depending on the input type really necessary? I am hoping the answer is "no". Thanks in advance. - Ken # ----------------------------------------------------------------------------------- require( zoo ); inp <- c( 5, 9, 4, 2, 1 ); inp2 <- c( 6, 6, 0, 4, 2 ); inp.zoo <- zoo( cbind( inp, inp2 ), as.Date("2003-02-01") + (0:(length(inp)-1))); lag.zerofill.list <- function( m, shift=1, ...) { c( rep(0,shift), m[-((length(m)-shift+1):length(m))] ); } lag.zerofill.zoo <- function( m, shift=1, ...) { k <- rbind( m[1:shift,], lag(m,-(shift))); k[1:shift,] <- 0; k; } lag.zerofill.list( inp ) # works ok lag.zerofill.zoo( inp.zoo ) # works ok -- View this message in context: http://www.nabble.com/How-to-avoid-switching-on-input-type--tp22637249p22637249.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.