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
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
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 >I would love to have an answer to this -- when I run into this kind of problem I usually end up using mapply: e.g., suppose I have mylist <- replicate(5,list(x=runif(10),y=runif(10)),simplify=FALSE) and I want to plot each element in a different color. I'd like to be able to do plot(0:1,0:1,type="n") lapply(mylist,plot,col=i) but instead I do mapply(function(x,i) points(x,col=i),mylist,1:5) would it be too ugly to have a special variable called INDEX that could be used within an sapply/lapply statement?