首页 > 解决方案 > 如何在 R 的包中导入运算符(来自 Matrix 的 %*%)?

问题描述

%*%使用Matrix::%*%. _ 尝试使用将其导入我自己的包时,我也遇到错误 #' @importFrom Matrix %*%.

# This works:
x <- ("test words for fun", "I like words as they are fun", "they have fun with words")
library(quanteda)
dtm <- quanteda::dfm(x, verbose = FALSE)
library(Matrix)
dtm_ok <- t(dtm) %*% dtm

# However, below does not work
dtm_ok <- t(dtm) Matrix::%*% dtm

#Further detaching the Matrix library result in an error
detach("package:Matrix", unload=TRUE)
dtm_ok <- t(dtm) %*% dtm

#neither does it work to import it for the package with 
#' @importFrom Matrix %*%

# However, when only trying to import the %*% from Matrix it says  Error: '%*%' is not an exported object from 'namespace:Matrix'
import::from("Matrix", "%*%")

所以不知道我应该如何进行。提前致谢。

标签: rmatrix

解决方案


#' @importFrom如果您的函数被封装在NAMESPACEroxygen2. 如果您想%*%在 R 会话中使用而不调用library(Matrix),我建议您查看 niceimport包。

例如,

import::from("magrittr", "%>%")

%>%将在不连接整个magrittrdplyr包装的情况下使管道可用。在您的情况下,如果您只想导入tfrom Matrix,您应该这样做

import::from("Matrix","t")
t
# standardGeneric for "t" defined from package "base"

# function (x) 
# standardGeneric("t")
# <environment: 0x55f0171c7520>
# Methods may be defined for arguments: x
# Use  showMethods("t")  for currently available ones.

这有点像from ... import ...python.

但是,请注意,如果您打算重新运行或共享代码,则需要明确记录导入这样的方法(因为使用基本方法时代码会中断)


推荐阅读