prob.of.ret <- function(nsteps = 100, nruns = 1000) { rt <- NULL; for(i in 1:nruns) { rt <- c(rt, match(0, cumsum(sample(c(-1,1), nsteps, repl=TRUE)))) } # Below it is explained how to build the final expression # in a typical manner: from the inside out! # --- Phase 0 #rt # --- Phase 1 #split(rt, factor(rt)); # ---- Phase 2 #lapply(split(rt, factor(rt)), function (x) { length(x)/nruns }); # ---- Phase 3 as.matrix(lapply(split(rt, factor(rt)), function (x) { length(x)/nruns })); }