以下代码是自定义R包中的函数。
#' @import Matrix
#' @export
asdf <- function(){
u <- Matrix(0,5,5)
rowSums(u)
}
当我加载包并执行它时,我得到以下输出。
> library(devtools); document(clean=TRUE); load_all()
Loading required package: roxygen2
Updating gm documentation
Loading gm
Loading required namespace: Matrix
Loading required package: Matrix
Writing gm.generate.Rd
Loading gm
> asdf
function(){
u <- Matrix(0,5,5)
rowSums(u)
}
<environment: namespace:gm>
>
> asdf()
Error in rowSums(u) (from tmp.R#5) : 'x' must be an array of at least two dimensions
因此,即使加载了Matrix包,即使在rowSums
中导入Matrix包,也不会调度Matrix包中的NAMESPACE
:
export(asdf)
import(Matrix)
在全局环境中,Matrix包确实已加载,并且rowSums
功能可用。
> showMethods(rowSums)
Function: rowSums (package base)
x="ANY"
x="CsparseMatrix"
x="ddenseMatrix"
x="denseMatrix"
x="dgCMatrix"
x="dgeMatrix"
x="diagonalMatrix"
x="dsCMatrix"
(inherited from: x="CsparseMatrix")
x="igCMatrix"
x="indMatrix"
x="lgCMatrix"
x="ngCMatrix"
x="RsparseMatrix"
x="TsparseMatrix"
但是,如果我在全局环境中定义相同的功能,一切正常:
> qwer <- function(){
u <- Matrix(0,5,5)
rowSums(u)
}
qwer <- function(){
+ u <- Matrix(0,5,5)
+ rowSums(u)
+ }
> qwer()
[1] 0 0 0 0 0
我很困惑。我做错了什么?
=============================================== =================
在NAMESPACE
档案中:
Package: hola
Type: Package
Title: What the package does (short line)
Version: 1.0
Date: 2014-01-03
Author: Who wrote it
Maintainer: Who to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What license is it under?
在DESCRIPTION
档案中:
export(asdf)
import(Matrix)
importFrom(Matrix,Matrix)
importFrom(Matrix,rowSums)
在R/asdf.R
档案中:
#' @import Matrix
#' @importFrom Matrix Matrix
#' @importFrom Matrix rowSums
#' @export
asdf <- function(){
u <- Matrix(0,5,5)
rowSums(u)
}
答案 0 :(得分:4)
您应该阅读1.5.6 Namespaces with S4 classes and methods
将此添加到您的NAMESPACE文件中:
import(Matrix)
或更好:
importFrom(Matrix, rowSums)
此外,还需要DESCRIPTION文件中的Imports: Matrix
。
裸体最小包装如下:
DESCRIPTION
档案:
Package: hola
Type: Package
Title: What the package does (short line)
Version: 1.0
Date: 2014-01-03
Author: Who wrote it
Maintainer: Who to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What license is it under?
Imports:
Matrix
NAMESPACE
档案:
export(asdf)
importFrom(Matrix,Matrix)
importFrom(Matrix,rowSums)
R/asdf.R
档案:
#' @importFrom Matrix Matrix
#' @importFrom Matrix rowSums
#' @export
asdf <- function(){
u <- Matrix(0,5,5)
rowSums(u)
}