Maximilian
Maximilian

Reputation: 4229

How to store values in embedded function

Yet another beginner question. Here is example:

store <- as.numeric()
multi.fun <- function(x) { t <- x*2; return(t) }
main.fun <- function(x) { store[i] <- multi.fun(x)+x; sum(tail(store,2)) }

x <- 1:10

ret <- as.numeric()

for(i in 1:10) {
 print(main.fun(x[i])); Sys.sleep(0.2)
}

Is it possible to assign values at each iteration to the store object?

EDIT: That means it would be evaluated inside the function so that the last sum(tail(..,2)) would give final result:

9 15 21 27 33 39 45 51 57

and the store[i] <- multi.fun(x)+x would give:

[1] 3 6 9 12 15 18 21 24 27 30

Upvotes: 1

Views: 44

Answers (1)

LyzandeR
LyzandeR

Reputation: 37879

I think what you probably need is the <<- operator which allows you to access objects in the Global environment (on this occasion).

Writing the main function as:

main.fun <- function(x) { store[i] <<- multi.fun(x)+x; sum(tail(store,2)) }

Your process does what you want it to do:

store <- as.numeric()
multi.fun <- function(x) { t <- x*2; return(t) }
main.fun <- function(x) { store[i] <<- multi.fun(x)+x; sum(tail(store,2)) }

x <- 1:10

ret <- as.numeric()

for(i in 1:10) {
  print(main.fun(x[i])); Sys.sleep(0.2)
}

Output:

[1] 3
[1] 9
[1] 15
[1] 21
[1] 27
[1] 33
[1] 39
[1] 45
[1] 51
[1] 57

However, it is usually not a good idea to use a function to change objects in the Global environment because it is prone to creating errors.

Upvotes: 3

Related Questions