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'
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With