for loop - R - use function n times on the same data set -
what efficient way apply function repetitively on same data set , give end result without using loop? e.g.
set.seed(123) # create arbitrary data frame mydf <- data.frame(a = rbinom(10, 5, .5), b = rbinom(10, 8, .5)) # silly function foo <- function(df) { df <- df * (1 + rnorm(1,0, .1)) df <- df + 5 df } # repeat function 5 times in row on same data frame (i in c(1:5)) { mydf <- foo(mydf) mydf }
answered @nrussel; example given, using recall()
gives elegant code. speed-wise, similar for
loop.
dofoo <- function(df, n) { if (n == 0) return(df) recall(foo(df), n - 1) } dofoo(mydf, 5)
Comments
Post a Comment