我似乎无法让 apply 函数访问/修改在外部声明的变量... 怎么回事?
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)
。 - bdemaresti
的值将在apply
的每次迭代(即对于df
的每一行)时被重置。我认为OP想要跟踪他们正在处理哪一行。 - Ricardo Saportaapply
,而是使用标准的for
循环:for (i in 1:nrow(df)) {...}
。目前,我们只能猜测他/她试图解决的潜在问题。 - bdemarest