gpt4 book ai didi

r - 在自定义 R 包中使用 "Matrix"包方法

转载 作者:行者123 更新时间:2023-12-02 07:42:15 27 4
gpt4 key购买 nike

以下代码是自定义 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 包,即使在 NAMESPACE 中导入了 Matrix 包,也不会调度 Matrix 包中的 rowSums:

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)
}

最佳答案

您应该阅读1.5.6 Namespaces with S4 classes and methods

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

import(Matrix)

或更好:

importFrom(Matrix, rowSums)

此外,描述文件中还需要导入:矩阵

最低限度的封装如下:

<小时/>

描述文件:

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
<小时/>

命名空间文件:

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)
}
<小时/>

关于r - 在自定义 R 包中使用 "Matrix"包方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20912128/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com