1

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...

Kay
  • 2,702
  • 6
  • 32
  • 48

1 Answers1

2

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
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • A more thourough search turned this SO-thread as very useful: http://stackoverflow.com/questions/17559390/why-is-assign-bad/17559641#17559641 that brought me to a more intuitive solution: `foo <- function() { a <- LETTERS[1:3] foobar <- lapply(X=a, FUN = function(x) sample(1000, 1)) names(foobar) <- a return(foobar) }` – Kay Sep 16 '13 at 08:57
  • @Kay but that is not in itself a function, which is what I thought you were going for. Some self-contained function that you could set the names of the object from within the function. – Simon O'Hanlon Sep 16 '13 at 09:01
  • I just noticed that and edited my comment! offtopic: thanks for the tip on raster::extract! – Kay Sep 16 '13 at 09:05
  • @Kay thanks! I'd still recommend using `setNames` as opposed to assigning and then using `names<-` inside the function. Because `setNames` was designed and provided for that very purpose! Glad it works. Cheers! – Simon O'Hanlon Sep 16 '13 at 09:08
  • Using a class may also useful. – user1436187 Sep 16 '13 at 11:21