On Apr 1, 2010, at 12:16 PM, Greg Gilbert wrote:


I have code that creates the same matrices , "a" and "b". The code creating "a" is not in a function and the code creating "b" is in a function. I would like to do operations on "b" like I can on "a", however I can't figure out how I can return a matrix (or data frame) from a function. Thanks for your
help!

r <- 5; c <- 5
a <- matrix(NA,nrow=5, ncol=5)
  for(i in 1:r) {
+       for (j in 1:c) {
+          if(i==j) a[i, j] <- i
+       }
+    }

diag(a)
[1] 1 2 3 4 5

data.out <- function(r, c) {
+    b <- matrix(NA,nrow=r, ncol=c)
+    for(i in 1:r) {
+       for (j in 1:c) {
+          if(i==j) b[i, j] <- i
+       }
+    }
+ }

data.out(5, 5)
diag(b)
Error in diag(b) : object 'b' not found

The "b" object only existed while the function was being processed. At the conclusion of the function's activities the b object did not get returned as the result . Had you returned "b" or made it the last object evaluated (inside the function), the results of data.out(5,5) it would have still been accessible. Try this instead

data.out <- function(r, c) {
    b <- matrix(NA,nrow=r, ncol=c)
    for(i in 1:r) {
       for (j in 1:c) {
          if(i==j) b[i, j] <- i
       }
    }
 b}  # or equivalently return(b)

> diag(data.out(5,5))
[1] 1 2 3 4 5


--
David

______________________________________________
[email protected] 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.

Reply via email to