Diana Wong
Diana Wong

Reputation: 11

Function which accesses/assigns to parent environment variables giving error

I trying to use this function

chan <- function(x) {
  for (i in x)
  {assign(i,sample(1:10,2))} 
  out <- data.frame(sapply(x,get))
  out
}

which x will be a list of string names, this function will assign 2 random numbers to each variable names and return it out as a data frame.

for example

 x <- c("e","f")

When I use this function, it gives error Error in FUN(..., ) : object ... not found

but if I don't use the function, just run the loop, it works. such as:

x <- c("e","f")
for (i in x)
 {assign(i,sample(1:10,1))}
 out <- data.frame(sapply(x,get))

I wonder what's wrong here.

Upvotes: 1

Views: 70

Answers (1)

Rorschach
Rorschach

Reputation: 32426

You can tell assign and get what environments to use when assigning/getting variables using pos (x will be in your global environment after this)

chan <- function(x) {
    for (i in x) {assign(i,sample(1:10,2), pos=1)}
    out <- data.frame(sapply(x, get, pos=1))
    out
}

or just assign in the local function environment

chan <- function(x) {
    e <- environment()
    for (i in x) {
        assign(i,sample(1:10,2), pos=e)
    }
    out <- data.frame(sapply(x, get, pos=e))
    out
}

Upvotes: 1

Related Questions