简体   繁体   中英

Returning multiple objects from function that were assigned inside function

I'd like to return all objects that were assigned inside a function,

like so:

foo <- function() { 
  as <- LETTERS[1:3]
  for(a in as) assign(a, sample(1000, 1))
  return(as) # obviously not working
  }

I know I maybe should wrap it in a list but can't get it to work...

I'd return it as a list as you suggest, and setNames is kinda designed for this...

foo <- function( n ) { 
  as <- LETTERS[1:n]
  setNames( replicate( n , sample( 1000 , 1 ) , simplify = FALSE  ), as )
  }

foo(3)
#$A
#[1] 286

#$B
#[1] 54

#$C
#[1] 791

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM