[R] function ave() with seq_along returning char sequence instead of numeric

Charles C. Berry ccberry at ucsd.edu
Tue Nov 1 17:24:50 CET 2016


On Mon, 31 Oct 2016, Jeff Newmiller wrote:

> The help page describes the first argument x as a numeric... it is not 
> designed to accept character,

Actually it is so designed, but not advertised as such. See below.

> so the fact that you get anything even close to right is just a bonus.
>
> As the doctor says, "if it hurts, don't do that".
>
> ave( rep( 1, length( v ), v, FUN=seq_along )
> --

[snip]


Reading the code of `ave` and then `split<-.default`, you will see subset 
replacement, "x[i]<- ...", on the argument 'x'. So, the issue is having 
FUN and that replacement (and possible coercion) yield something 
useful/sensible. In other words, class(x) need not be "numeric".

For instance, operating on "Date" objects:

> # start at 2016-01-02, step 10 days, ...
> x <- as.Date("2016-01-01")+seq(1,1000,by=10)
> z <- rep(1:10, 10)
>  class(ave(x,z)) # Date class is preserved
[1] "Date"
> ave(x,z) # mean date
   [1] "2017-03-27" "2017-04-06" "2017-04-16" "2017-04-26" ... 
> ave(x,z,FUN=min) # earliest date
   [1] "2016-01-02" "2016-01-12" "2016-01-22" "2016-02-01" ...

However, trying to describe this feature in the help page without a lot of 
detail and examples might confuse more users than it would enlighten.

--
Chuck



More information about the R-help mailing list