I can't seem to make apply function access/modify a variable that is declared outside... what gives?
x = data.frame(age=c(11,12,13), weight=c(100,105,110)) x testme <- function(df) { i <- 0 apply(df, 1, function(x) { age <- x[1] weight <- x[2] cat(sprintf("age=%d, weight=%d\n", age, weight)) i <- i+1 #this could not access the i variable in outer scope z <- z+1 #this could not access the global variable }) cat(sprintf("i=%d\n", i)) i } z <- 0 y <- testme(x) cat(sprintf("y=%d, z=%d\n", y, z)) Results:
age=11, weight=100 age=12, weight=105 age=13, weight=110 i=0 y=0, z=0
testme, and then toapply:testme <- function(x, z) {andapply(df, 1, function(x, i, z) {}, i, z)iwill be reset at iteration ofapply(ie, for every row ofdf). I think the OP wants to track which row they are onapply, but instead a standardforloop:for (i in 1:nrow(df)) {...}. Currently, we can only guess at the underlying problem he/she is trying to solve.