Home > Enterprise >  Why does my R function works inside but not when called from outside?
Why does my R function works inside but not when called from outside?

Time:05-09

I have a R function which works when I select its commands and run them manually. The function manipulates a Dataframe. When called from outside, nothing changes in the dataframe?

My function:

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
  
}

This function works when I select all the lines inside and run it (RStudio) but not when doing the following:

fun() // This wont work

My Dataframe:

C1 C2 C3
1 0 0 0
2 1 2 0
3 0 0 0
4 1 2 0

Output from running function lines from inside:

C1 C2 C3
1 0 0 0
2 1 3 0
3 0 0 0
4 1 3 0

Output from calling fun()

C1 C2 C3
1 0 0 0
2 1 2 0
3 0 0 0
4 1 2 0

CodePudding user response:

When you assign values using the <- operator, the values are assigned in the local environment - in your case, it is the environment in which the function fun is executed.DF is defined in the global environment, which is the parent environment of the function fun. In order to assign values in the parent environment, you need to do the assignments using the <<- operator.

See

?`<<-`
  • Related