I'd like to perform return variable assignments like matlab. For example, the following function would return A, B, and c to the script that called it.
================================= function [A,B,c] = simple(m,n) A=[ 3 2; 3 3] B=m c=1:n ================================= I'd like to do similar assignments in R, but I seem to be able to only return one variable. I tried to use a list to return all the arguments, but then each has to be referred to using the list. For example: ================================= simple <- function(m,n) { A=matrix(c(3,3,2,3),2,2) B=m c=1:n list(A=A,B=B,c=c) } > stuff=simple(2,3) > stuff $A [,1] [,2] [1,] 3 2 [2,] 3 3 $B [1] 2 $c [1] 1 2 3 ================================= Then I could assign each variable like this (which is what I'd like to avoid): ================================= A=stuff$A B=stuff$B c=stuff$c rm(stuff) #stuff isn't needed anymore. ================================= I've even toyed with the superassignment operator, which also works, but I think it doesn't work for functions of functions. The following example works. ================================= simple2 <- function(m,n) { A <<- matrix(c(3,3,2,3),2,2) B <<- m c <<- 1:n } > stuff2=simple2(2,3) > stuff2 [1] 1 2 3 > A [,1] [,2] [1,] 3 2 [2,] 3 3 > B [1] 2 > c [1] 1 2 3 ================================= In the example below, I call the function ten inside the function nine. I'm expecting that the variable b should change only in the function nine (and not in the global environment). In other words, I think the line "(nine) b= 9" should be "(nine) b= 10". Can someone help me know how to do this correctly? -Scott ================================= nine = function(a) { b <- 9 ten(a) print(paste("(nine) b=",b)) } ten = function(d) { b <<- 10 print(paste("(ten) b=",b)) print(paste("(ten) d=",d)) d } > nine(5) [1] "(ten) b= 10" [1] "(ten) d= 5" [1] "(nine) b= 9" > b [1] 10 ================================= [[alternative HTML version deleted]] ______________________________________________ R-help@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.