【发布时间】:2012-11-18 09:00:09
【问题描述】:
我似乎无法让应用函数访问/修改在外部声明的变量...什么给出?
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=0
y=0, z=0
【问题讨论】:
-
你需要将变量传递给
testme,然后传递给apply:testme <- function(x, z) {和apply(df, 1, function(x, i, z) {}, i, z) -
@bdemarest:这不起作用,因为
i的值将在apply的迭代中重置(即,对于df的每一行)。我认为 OP 想要跟踪他们在哪一行 -
@RicardoSaporta,你说的很对。可能 OP 最好不要使用
apply,而是使用标准的for循环:for (i in 1:nrow(df)) {...}。目前,我们只能猜测他/她试图解决的潜在问题。 -
这只是一个测试片段来证明我遇到的问题 :-) 结果我应该将结果返回给调用者,即将应用调用的结果分配给另一个变量。这是一种更好的功能风格。