r - Function which accesses/assigns to parent environment variables giving error -


i trying use function

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

which x list of string names, function assign 2 random numbers each variable names , return out data frame.

for example

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

when use function, gives error error in fun(..., ) : object ... not found

but if don't use function, run loop, works. such as:

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

i wonder what's wrong here.

you can tell assign , get environments use when assigning/getting variables using pos (x in global environment after this)

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

or assign in local function environment

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

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -