How to reuse code in an R function? -
i have block of code want use several times inside function (let's call myfunction). naturally want avoid duplicating block of code, can't find way of reusing short of putting in external file , sourcing each time.
the first thing tried put duplicate code in internal mini-function no arguments (let's call internalfunction. meant call internalfunction needed; however, masked objects output internalfunction main environment of myfunction.
i tried using <<- operator assign output objects within internalfunction, made available main environment of myfunction. unfortunately, makes objects available global r environment outside myfunction, want avoid.
is there way of writing block of r code object , calling that, or sourcing object instead of file? a) avoid duplicate code , b) include code within single file.
i think want easy way return multiple values calling function, can done list, follows:
maxmin <- function(i1,i2){ if (i1>i2){ mx <- i1 mn <- i2 } else { mn <- i1 mx <- i2 } rv <- list(min=mn,max=mx) return(rv) } r1 <- maxmin(3,4) r2 <- maxmin(6,5) print(sprintf("minimums %d %d",r1$min,r2$min)) print(sprintf("maximums %d %d",r1$max,r2$max)) edit: got rid of quotes list element names, not necessary
Comments
Post a Comment