用file :: function命名R文件的最简单方法是什么

问题描述

回答这个问题的标准

提供以下功能(在其自己的脚本中)

end = [
 {node: 1,cat: "a"},{node: 2,{node: 3,]

启用以下设置的最少量的设置是什么

# something.R
hello <- function(x){
    paste0("hello ",x)
}

上下文

在python中,拥有一个包含一些代码的目录非常简单,并将其用作

library(something)
x <- something::hello('Sue')
# x Now has value: "hello Sue"

我不确定如何在R中做类似的事情。

我知道这里有# here foo is a directory from foo import bar bar( ... ) ,但这将所有内容都放入了全局名称空间。我也知道有source(file.R)提供了library(package)。我不确定的是R中是否有一种简单的方法来使用此命名空间。我搜索过的包装教程似乎很复杂(与Python相比)。

解决方法

我不知道为一个快速功能创建名称空间是否有真正的好处。 (我认为)这不是应该的样子。

但是无论如何,这是一个非常简单的解决方案:

首次安装一次:install.packages("namespace")

您要在名称空间中调用的函数:

hello <- function(x){
  paste0("hello ",x)
}

创建名称空间,分配功能并导出

ns <- namespace::makeNamespace("newspace")
assign("hello",hello,env = ns)
base::namespaceExport(ns,ls(ns))

现在您可以使用新的命名空间调用函数

newspace::hello("you")
,

这是我所知道的使用RStudio生成软件包的最快工作流程。默认程序包已经包含一个hello函数,我用您的代码重写了该函数。

请注意,还有一个框“基于源文件创建软件包”,我没有使用过,但是您可以使用。

enter image description here

以这种方式完成的程序包将包含导出的未记录的未经测试的功能。

如果您想学习如何记录,是否导出,编写测试和运行检查,包括函数以外的其他对象,包括编译后的代码,在github上共享,在CRAN上共享。This book描述了所使用的工作流程设计成千上万的用户,因此您通常可以独立阅读各节。


如果您不想通过GUI进行操作,则可以使用utils::package.skeleton()来构建软件包文件夹,并使用remotes::install_local()来安装它:

可复制的设置

# create a file containing function definition

# where your current function is located
function_path <- tempfile(fileext = ".R")
cat('
hello <- function(x){
  paste0("hello ",x)
}
',file = function_path)

# where you store your package code
package_path <- tempdir()

解决方案:

# create package directory at given location
package.skeleton("something",code_file = file_path,path = package_path)
# remove sample doc to make remotes::install_local happy
unlink(file.path(package_path,"something","man/"),TRUE) 
# install package
remotes::install_local(file.path(package_path,"something"))