[R] extract index during execution of sapply
Martin Morgan
mtmorgan at fhcrc.org
Fri Jun 22 15:20:27 CEST 2007
Christian,
A favorite of mine is to use lexical scope and a 'factory' model:
> fun_factory <- function() {
+ i <- 0 # 'state' variable(s), unique to each fun_factory
+ function(x) { # fun_factory return value; used as sapply FUN
+ i <<- i + 1 # <<- assignment finds i
+ x^i # return value of sapply FUN
+ }
+ }
>
> sapply(1:10, fun_factory())
[1] 1 4 27 256 3125 46656
[7] 823543 16777216 387420489 10000000000
Christian Bieli <christian.bieli at unibas.ch> writes:
> Hi there
> During execution of sapply I want to extract the number of times the
> function given to supply has been executed. I came up with:
>
> mylist <- list(a=3,b=6,c=9)
> sapply(mylist,function(x)as.numeric(gsub("[^0-9]","",deparse(substitute(x)))))
>
> This works fine, but looks quite ugly. I'm sure that there's a more
> elegant way to do this.
>
> Any suggestion?
>
> Christian
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
--
Martin Morgan
Bioconductor / Computational Biology
http://bioconductor.org
More information about the R-help
mailing list