Generic 'diff'
Wacek Kusnierczyk wrote:
Stavros Macrakis wrote:
[...]
I am not talking about creating a new class with an analogue to the
subtraction function. I am talking about a function which applies another
function to a sequence and its lagged version.
Functional arguments are used all over the place in R's base package
(Xapply, sweep, outer, by, not to mention Map, Reduce, Filter, etc.) and
they seem perfectly natural here.
[...]
as you say, it's trivial to implement an extended diff, say difff,
reusing code from diff:
difff = function(x, ...)
UseMethod('difff')
difff.default = function(x, lag=1, differences=1, fun=`-`, ...) {
ismat = is.matrix(x)
xlen = if (ismat) dim(x)[1L] else length(x)
if (length(lag) > 1L || length(differences) > 1L || lag < 1L ||
differences < 1L)
stop("'lag' and 'differences' must be integers >= 1")
btw., the error message here is confusing:
lag = 1:2
diff(1:10, lag=lag)
# Error in diff.default(1:10, lag = lag) :
# 'lag' and 'differences' must be integers >= 1
is.integer(lag)
# TRUE
all(lag >= 1)
# TRUE
what is meant is that lag and differences must be atomic 1-element
vectors of positive integers. or rather integer-representing numerics:
lag = 1
diff(1:5, lag=1)
# fine
is.integer(lag)
# FALSE
(the usual confusion between 'integer' as the underlying representation
and 'integer' as the represented number.)
vQ