[R] Newbie: Examples on functions callling a library etc.
Steven McKinney
smckinney at bccrc.ca
Fri Aug 29 04:48:02 CEST 2008
Hi Ed,
Here's a simple example showing your needs:
myfun <- function(n1, n2, n3) {
mat1 <- matrix(rep(1), nrow = n1, ncol = 3)
mat2 <- matrix(rep(2), nrow = n2, ncol = 4)
mat3 <- matrix(rep(3), nrow = n3, ncol = 5)
require("survival") ## make sure the package you need is loaded
mypkgfun <- survival::is.Surv ## Use the '::' and ':::' extractors to get visible and hidden functions respectively from the package
list(mat1 = mat1, mat2 = mat2, mat3 = mat3, mypkgfun = mypkgfun) ## Return the items in a list
}
## Now invoke the function
foo <- myfun(n1 = 1, n2 = 1, n3 = 5)
## and look at the returned results
foo
> myfun <- function(n1, n2, n3) {
+ mat1 <- matrix(rep(1), nrow = n1, ncol = 3)
+ mat2 <- matrix(rep(2), nrow = n2, ncol = 4)
+ mat3 <- matrix(rep(3), nrow = n3, ncol = 5)
+
+ require("survival")
+ mypkgfun <- survival::is.Surv
+
+ list(mat1 = mat1, mat2 = mat2, mat3 = mat3, mypkgfun = mypkgfun)
+ }
>
> foo <- myfun(n1 = 1, n2 = 1, n3 = 5)
>
> foo
$mat1
[,1] [,2] [,3]
[1,] 1 1 1
$mat2
[,1] [,2] [,3] [,4]
[1,] 2 2 2 2
$mat3
[,1] [,2] [,3] [,4] [,5]
[1,] 3 3 3 3 3
[2,] 3 3 3 3 3
[3,] 3 3 3 3 3
[4,] 3 3 3 3 3
[5,] 3 3 3 3 3
$mypkgfun
function (x)
inherits(x, "Surv")
<environment: namespace:survival>
>
HTH
Steve McKinney
-----Original Message-----
From: r-help-bounces at r-project.org on behalf of Eduardo M. A. M.Mendes
Sent: Thu 8/28/2008 5:43 PM
To: r-help at r-project.org
Subject: [R] Newbie: Examples on functions callling a library etc.
Hello
R is pretty new to me. I need to write a function that returns three
matrices of different dimensions. In addition, I need to call a function
from a contributed package with the function. I have browsed several
manuals and docs but the examples on them are either very simple or
extremely hard to follow.
Many thanks
Ed
[[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.
More information about the R-help
mailing list