如何从 R 应用函数访问全局/外部作用域变量? [英] how to access global/outer scope variable from R apply function?
本文介绍了如何从 R 应用函数访问全局/外部作用域变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎无法让应用函数访问/修改在外部声明的变量......是什么给出了?
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
", 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
", i))
i
}
z <- 0
y <- testme(x)
cat(sprintf("y=%d, z=%d
", y, z))
结果:
age=11, weight=100
age=12, weight=105
age=13, weight=110
i=0
y=0, z=0
推荐答案
使用 <<-
运算符,您可以写入外部作用域中的变量:
Using the <<-
operator you can write to variables in outer scopes:
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
", 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
", i))
i
}
z <- 0
y <- testme(x)
cat(sprintf("y=%d, z=%d
", y, z))
这里的结果:
age=11, weight=100
age=12, weight=105
age=13, weight=110
i=3
y=3, z=3
请注意,使用 <<-
是危险的,因为您会破坏作用域.仅在确实有必要时才这样做,如果这样做,请清楚地记录该行为(至少在更大的脚本中)
Note that the usage of <<-
is dangerous, as you break up scoping. Do this only if really necessary and if you do, document that behavior clearly (at least in bigger scripts)
这篇关于如何从 R 应用函数访问全局/外部作用域变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文