簡體   English   中英

在自定義R包中使用“Matrix”包方法

[英]Using “Matrix” package methods in a custom R package

以下代碼是自定義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

因此,即使矩陣包被加載, rowSums在矩陣包是沒有得到派出即使矩陣封裝在進口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)
}

您應該閱讀帶有S4類和方法的1.5.6命名空間

將其添加到您的NAMESPACE文件中:

import(Matrix)

或更好:

importFrom(Matrix, rowSums)

此外,還需要Imports: Matrix描述文件中的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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM