[R] outputting functions in lapply

baptiste auguie baptiste.auguie at googlemail.com
Mon Dec 7 15:37:06 CET 2009


Hi,

I was about to send the exact same answer as you just received, so
I'll add a note instead. Your problem looks a bit like Currying,

Curry <-  # original from roxygen
function (f, ..., .left=TRUE)
{
    .orig = list(...)
    function(...){
	if(.left) {args <- c(.orig, list(...))} else {args <- c(list(...), .orig)}
	 do.call(f, args)
	}
}

Curry( function(k, r) print(paste(r, "<- r | k ->", k)), k=2)(1)
# "1 <- r | k -> 2"

Best,

baptiste



2009/12/7 Rune Schjellerup Philosof <rphilosof at health.sdu.dk>:
> How come the k is 3 in all of this output?
> I expected it to be equal to r.
>
>> tmp3 <- lapply(1:3, function(k) function(r) print(paste(r, "<- r | k
> ->", k)))
>> for (i in 1:3) { tmp3[[i]](i) }
> [1] "1 <- r | k -> 3"
> [1] "2 <- r | k -> 3"
> [1] "3 <- r | k -> 3"
>
> --
> Med venlig hilsen
>
> Rune Schjellerup Philosof
> Ph.d-stipendiat, Forskningsenheden for Biostatistik
>
> Telefon: 6550 3607
> E-mail:  rphilosof at health.sdu.dk
> Adresse: J.B. Winsløwsvej 9, 5000 Odense C
>
> SYDDANSK UNIVERSITET
> _______________________________________________________________
> * Campusvej 55 * 5230 * Odense M * 6550 1000 * www.sdu.dk
>
> ______________________________________________
> 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.
>




More information about the R-help mailing list