Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load a library dynamically? [duplicate]

Tags:

r

Sorry for asking easy question. I am a R beginner. I tried to load a library run-time, e.g.

x<-"snow"; library(eval(x))

Result:

Error in library(eval(x)) : 'package' must be of length 1.

I would appreciate it if anyone gave me some solutions.

like image 715
YYY Avatar asked Oct 22 '13 19:10

YYY


People also ask

How are dynamic libraries loaded?

Dynamic libraries are loaded at runtime and are not included in the executable. This reduces the size of executable files. Dynamic libraries use relocatable code format. This code is turned into absolute code by the runtime linker.

Are dynamic libraries reusable?

Functions are blocks of code that are reusable throughout a program. Using them saves time, removing the need to rewrite code multiple times. Libraries, like functions also save time in that they make functiones reusable in multiple programs.

How do I create a Dynamic Library?

The way to create a Dynamic Library in Linux is with the gcc command using the -c to generate the object files (.o) from the source files (. c) and the -fPIC to make the code position independent. Thus, the following command makes a bunch of .o files from each .

How are shared libraries loaded?

Shared libraries are the most common way to manage dependencies on Linux systems. These shared resources are loaded into memory before the application starts, and when several processes require the same library, it will be loaded only once on the system. This feature saves on memory usage by the application.


2 Answers

Use character.only=TRUE. See the help page for library, with ?library.

> library(x, character.only=TRUE)
like image 61
Aaron left Stack Overflow Avatar answered Oct 05 '22 22:10

Aaron left Stack Overflow


I'd recommend to use require instead of library.

  • require returns a logical indicating whether the package was successfully loaded, i.e. you can use it in constructs like

    if (require (x, character.only = TRUE))
        ...
    

    On contrast, library will by default stop with an error if the package is not available (you can change this behaviour by logical.return = TRUE, though).

  • In case the package is loaded already, and this part of code is executed often, speed may matter: require is almost 20x faster than library on my laptop if the package is loaded already. If not, it calls library.

like image 44
cbeleites unhappy with SX Avatar answered Oct 05 '22 21:10

cbeleites unhappy with SX