[R] interaction of shingles and tapply()

jim holtman jholtman at gmail.com
Wed Nov 28 03:32:43 CET 2007


One way to get rid of the 'for' loop:

tapply.shingle <- function(x, s, fn, ...){
    unlist(lapply(levels(s), function(.val) mean(x[s > .val[1] & s <
.val[2]], ...))
}


On Nov 27, 2007 8:56 PM, Roger Levy <rlevy at ucsd.edu> wrote:
> I'm interested in a version of tapply() that operates with shingles
> instead of factors.  For instance:
>
> x <- c(1,1,2,2,3,3)
> y <- c(1,1,1,0,0,0)
>
> s <- shingle(x,intervals=cbind(c(0.5,1.5),c(2.5,3.5)))
>
>
> # the following function should exist!
> tapply.shingle(x,s,mean)  # returns the vector c(0.75,0.25)
>
>
> I've written such a function as follows:
>
>
> tapply.shingle <- function(x,s,fn,...) {
>   result <- c()
>   for(l in levels(s)) {
>     x1 <- x[s > l[1] & s < l[2]]
>     result <- c(result, fn(x1,...))
>   }
>   result
> }
>
>
> However, I'm not thrilled with the for() loop, and I don't see any way
> to generalize this function to handle lists of shingles instead of
> individual shingles, except to use recursion.  Does anyone have any
> suggestions or thoughts?
>
> Many thanks,
>
> Roger
>
> ______________________________________________
> R-help at 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list