[R] assigning multiple outputs

Joshua Wiley jwiley.psych at gmail.com
Fri Nov 18 09:14:39 CET 2011


Hi Sachin,

What you have probably is the best way.  In the vast majority of
cases, functions have no business doing assignment outside of
themselves.  If you find you have a function producing such disparate
output that it makes no sense for all the output to be stored
together, it might be better to create two separate functions.

Remember, functions usually return values, not make changes to the
environment.  Consider:

a <- "an object containing valuable results, that potentially took a
very long time to compute"

f <- function() {
  x <- 1
  assign("a", x, envir = .GlobalEnv)
}

results <- f()

results
a ## what happened to my data?!?!?!

Sincerely,

Josh

P.S. but I showed you the way, if you still think its a good idea in
your case, assign() will do it.

On Fri, Nov 18, 2011 at 12:01 AM, Sachinthaka Abeywardana
<sachin.abeywardana at gmail.com> wrote:
> Hi All,
>
> So I figured out how to do multiple outputs, but whats the best/
> recommended way of assigning them.
>
> f<-function{a=1; b=1; list(a,b)}
>
> I want to be able to say assign into a and b straight away rather that
> doing a=f()[[1]] and b=f()[[2]]. It would be best if I can get around this
> without having to assigning this to a third dummy variable.
>
> Thanks,
> Sachin
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list