为什么我的 R 函数在内部有效,但从外部调用时却无效?
Why does my R function works inside but not when called from outside?
我有一个 R 函数,当我 select 它的命令和手动 运行 它们时,它可以工作。该函数操作一个 Dataframe。从外部调用时,数据帧没有任何变化?
我的函数:
fun <- function(){
# If C2 value greater than 0 and less than 10 and C1 value is 1
index <- DF$C2 < 10 & DF$C2 > 0 & DF$C1 == 1
# Then increment C2 value by 1
DF$C2[index] <- DF$C2[index] + 1
# Other logic
DF_processed <- t(apply(DF[Index,], 1, someFun))
DF[Index, ] <- DF_processed
# If C2 value greater or equal to 10, reset C1,C2 to 0
otherIndex <- DF$C2 >= 10
DF$C1[aboutToRecoverIndex] <- DF$C2[otherIndex] <- 0
}
这个函数在我select里面的所有行和运行它(RStudio)时有效,但在执行以下操作时无效:
fun() // This wont work
我的数据框:
C1
C2
C3
1
0
0
0
2
1
2
0
3
0
0
0
4
1
2
0
来自运行ning函数行的输出来自内部:
C1
C2
C3
1
0
0
0
2
1
3
0
3
0
0
0
4
1
3
0
调用 fun() 的输出
C1
C2
C3
1
0
0
0
2
1
2
0
3
0
0
0
4
1
2
0
当您使用 <-
运算符赋值时,值是在本地环境中赋值的 - 在您的例子中,它是执行函数 fun
的环境。DF
定义在全局环境中,是函数fun
的父环境。为了在父环境中分配值,您需要使用 <<-
运算符进行分配。
见
?`<<-`
我有一个 R 函数,当我 select 它的命令和手动 运行 它们时,它可以工作。该函数操作一个 Dataframe。从外部调用时,数据帧没有任何变化?
我的函数:
fun <- function(){
# If C2 value greater than 0 and less than 10 and C1 value is 1
index <- DF$C2 < 10 & DF$C2 > 0 & DF$C1 == 1
# Then increment C2 value by 1
DF$C2[index] <- DF$C2[index] + 1
# Other logic
DF_processed <- t(apply(DF[Index,], 1, someFun))
DF[Index, ] <- DF_processed
# If C2 value greater or equal to 10, reset C1,C2 to 0
otherIndex <- DF$C2 >= 10
DF$C1[aboutToRecoverIndex] <- DF$C2[otherIndex] <- 0
}
这个函数在我select里面的所有行和运行它(RStudio)时有效,但在执行以下操作时无效:
fun() // This wont work
我的数据框:
C1 | C2 | C3 | |
---|---|---|---|
1 | 0 | 0 | 0 |
2 | 1 | 2 | 0 |
3 | 0 | 0 | 0 |
4 | 1 | 2 | 0 |
来自运行ning函数行的输出来自内部:
C1 | C2 | C3 | |
---|---|---|---|
1 | 0 | 0 | 0 |
2 | 1 | 3 | 0 |
3 | 0 | 0 | 0 |
4 | 1 | 3 | 0 |
调用 fun() 的输出
C1 | C2 | C3 | |
---|---|---|---|
1 | 0 | 0 | 0 |
2 | 1 | 2 | 0 |
3 | 0 | 0 | 0 |
4 | 1 | 2 | 0 |
当您使用 <-
运算符赋值时,值是在本地环境中赋值的 - 在您的例子中,它是执行函数 fun
的环境。DF
定义在全局环境中,是函数fun
的父环境。为了在父环境中分配值,您需要使用 <<-
运算符进行分配。
见
?`<<-`