How to load packages in R

无人久伴 提交于 2019-12-06 03:51:16

问题


I have successfully installed the tm package, which is located in: C:\Users\JustinLiang\Documents\R\win-library\3.0

After type library(), it shows me the R packages available list:

Packages in library ‘C:/Users/JustinLiang/Documents/R/win-library/3.0’:

tm Text Mining Package

Packages in library ‘C:/Program Files/R/R-3.0.2/library’:

however, when I try to load the package: library(tm), it shows me an error:

Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) : 
  there is no package called ‘slam’
Error: package or namespace load failed for ‘tm’

回答1:


The package has to be first installed before you load the package using library(). To install any package, open the R or RStudio shell and execute the following

install.packages("tm",dependencies=TRUE)

This will ask you to select the mirror and it will install it for you. If you use RStudio, you can easily do it from the Tools menu as shown below (Tools -> Install Packages -> Name of the package you want to install).

And then finally, you can invoke the library("name of the package installed") function.




回答2:


When you use install.packages(), my sense would be to recommend you call with the parameter dependencies = TRUE. This will install both the required library and its dependencies. Personally, I would avoid all the complexities and use the following solution:

requiredPackages <- c("ascii", "devtools","plyr","dplyr","tidyr")

ipak <- function(pkg)
{
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

ipak(requiredPackages)

this code both checks if the package is installed and if not installed will install the library and its dependencies. It then loads the package via require(). nb. Personally, I prefer require() to library() as you can check the return code of a call to require()...

My sense is that the above code may make for easier code readability as it removes the need to have library() calls through the code.

I hope the above helps - happy new year



来源:https://stackoverflow.com/questions/20530738/how-to-load-packages-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!