Calling Library() in R with a Variable as the Argument

Calling library() in R with a variable as the argument

How about library(...,character.only = TRUE)?

Passing variables to the library function

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)
}
}

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

a logical indicating whether package or help can be assumed to be character strings.

Forcing R to apply a function or call a variable inside an argument of set_args function

You can splice the argument using the bang bang operator !! :

library(parsnip)

tree_numbers = c(500, 1000)
boost_tree() %>% set_args(tree_depth = !! tree_numbers[1])

#> Boosted Tree Model Specification (unknown)
#>
#> Main Arguments:
#> tree_depth = 500
#>
#> Computational engine: xgboost

Created on 2021-12-17 by the reprex package (v2.0.1)

Load R package from character string

Use the character.only argument

foo <- "ggplot2"
library(foo,character.only=TRUE)

Using ~ call in R with dynamic variables

You can try this, you need to pass a character to variable. It's much easier that way and if you have 10 variables on X side, you can easily iterate through them:

getFormula <- function(variable){
as.formula(paste(variable,"~ Sepal.Length + Sepal.Width + Species"))
}

petal.length.formula <- getFormula("Petal.Length")
petal.width.formula <- getFormula("Petal.Width")

lm(petal.length.formula,data=iris)
Call:
lm(formula = petal.length.formula, data = iris)

Coefficients:
(Intercept) Sepal.Length Sepal.Width Speciesversicolor
-1.63430 0.64631 -0.04058 2.17023
Speciesvirginica
3.04911

You can also try reformulate, as suggested by @BenBolker and @MrFlick:

getFormula <- function(variable){
reformulate(c("Sepal.Length","Sepal.Width","Species"),
response = variable, intercept = TRUE)
}

lm(getFormula("Petal.Length"),data=iris)

Call:
lm(formula = getFormula("Petal.Length"), data = iris)

Coefficients:
(Intercept) Sepal.Length Sepal.Width Speciesversicolor
-1.63430 0.64631 -0.04058 2.17023
Speciesvirginica
3.04911


Related Topics



Leave a reply



Submit