使用<<-
运算符,您可以写入外部作用域中的变量:
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))
结果在这里:
age=11, weight=100
age=12, weight=105
age=13, weight=110
i=3
y=3, z=3
请注意,使用<<-
是危险的,因为你打破了范围。仅在确实必要时才执行此操作,并且如果这样做,请清楚地记录该行为(至少在较大的脚本中)