Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't figure out error in lapply

Tags:

r

lapply

apply

I am a beginner having picked up R a few weeks ago and am trying to learn the apply family. Can't figure out how to use lapply and it is maddenning. Yes, I looked up ?lapply and several books including R in a nutshell and R cookbook and still can't figure out what am I doing wrong.

lapply(X = c("ggplot2", "gtable", "grid"), library)
## Error: 'package' must be of length 1
lapply(X = c("ggplot2", "gtable", "grid"), FUN = function(x) library(x))
## Error: there is no package called 'x'
lapply(X = c("ggplot2", "gtable", "grid"), FUN = library)
## Error: 'package' must be of length 1
x = c("ggplot2", "gtable", "grid")
lapply(x, library)
## Error: 'package' must be of length 1
lapply(x, FUN = function(x) library(x))
## Error: there is no package called 'x'
like image 762
K Owen - Reinstate Monica Avatar asked Dec 21 '22 08:12

K Owen - Reinstate Monica


2 Answers

There is nothing wrong with your lapply() per se, but the problem is that library() evaluates its arguments in a slightly special way.

This means you need to use

library(pkg.name, character.only=TRUE)

This is rather obscure in the help for ?library:

package, help
the name of a package, given as a name or literal character string, or a character string, depending on whether character.only is FALSE (default) or TRUE).

What this means is that if you supply a character string to library(), you must set character.only to TRUE.

So, try this:

lapply(x, library, character.only=TRUE)

Then you will probably want to call require() instead of library(), and simplify the results with sapply:

sapply(x, require, character.only=TRUE)
ggplot2  gtable    grid 
   TRUE    TRUE    TRUE 

The difference is that require() returns a single logical value indicating whether the package was loaded successfully or not.

like image 86
Andrie Avatar answered Jan 19 '23 12:01

Andrie


Try this for example:

 lapply(X = c("ggplot2", "gtable", "grid"), library,character.only =T)

see ?library

package, help the name of a package, given as a name or literal character string, or a character string, depending on whether character.only is FALSE (default) or TRUE).

So here the when you try for example:

lapply(X = c("ggplot2", "gtable", "grid"), FUN = function(x) library(x))
## Error: there is no package called 'x'

you get an error because library get x as an argument and try to loa the package of name = 'x'

like image 39
agstudy Avatar answered Jan 19 '23 10:01

agstudy