将变量传递给库函数 [英] Passing variables to the library function
问题描述
package <- c("car","ggplot2","pastecs","psych")
for (i in package){
if (!(i %in% rownames(installed.packages()))){
install.packages(i)
} else{
print(paste(i,"has been installed"))
library(i)
}
}
我写了一个循环来查看软件包是否已安装,以及是否可用,库应该加载它.
I wrote a loop to see whether the package is installed, and if it is available, the library should load it.
However I got an error: there is no package called 'i'
为什么不能将变量 i
中的值传递给 library
函数?
Why can't I pass the value in variable i
to the library
function ?
推荐答案
这是您的代码的更简单版本(包含@csgillespie 的建议):
Here's a simpler version of your code (incorporating @csgillespie's suggestion):
p <- c("car","ggplot2","pastecs","psych")
for(i in seq_along(p)) {
if(!require(p[i], character.only=TRUE)) {
install.packages(p[i])
library(p[i], character.only=TRUE)
}
}
请注意,由于库
和 require
中的非标准评估,您的代码无法正常工作. character.only
参数可解决此问题(根据文档?库
):
Note that your code does not work because of non-standard evaluation in library
and require
. The character.only
argument resolves this (per documentation ? library
):
character.only
逻辑,表示可以将包或帮助视为字符串.
character.only
a logical indicating whether package or help can be assumed to be character strings.
这篇关于将变量传递给库函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!