[R] Using a Data Frame/Matrix outside a function

Greg Gilbert gregory.e.gilbert at gmail.com
Thu Apr 1 18:16:14 CEST 2010


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
> 

-- 
View this message in context: http://n4.nabble.com/Using-a-Data-Frame-Matrix-outside-a-function-tp1748285p1748285.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list