Tom
Tom

Reputation: 2351

Turning code (instead of data) into a vector

I have the following code:

install.packages("microbenchmark")
install.packages("readxl")
install.packages("data.table")

I would like to create a vector of a variable amount of package names without having to actually write the vector (these package names are or not necessarily installed). Desired output:

vector <- c("microbenchmark","readxl", "data.table")

I thought I would feed the packages to vector as a string and go from there:

input <- 'install.packages("microbenchmark")
install.packages("readxl")
install.packages("data.table")'

vector <- gsub("install.packages\(", " ", input)

But it does not even create the vector properly. How should I do this?

Upvotes: 1

Views: 55

Answers (3)

Uwe
Uwe

Reputation: 42564

For the sake of completeness, here is an approach which uses str_match_all() from the stringr package to extract all characters which are enclosed in double quotes ":

library(magrittr) # piping used for readability
vector <- stringr::str_match_all(input, '"(.*)"') %>% 
    extract2(1) %>% 
    .[, 2]

vector
[1] "microbenchmark" "readxl"         "data.table"

str_match_all() returns a list of character matrices. Therefore, the subsequent steps are required to extract the vector.

Data

input <- 'install.packages("microbenchmark")
install.packages("readxl")
install.packages("data.table")'

input
[1] "install.packages(\"microbenchmark\")\ninstall.packages(\"readxl\")\ninstall.packages(\"data.table\")"

Upvotes: 1

Onyambu
Onyambu

Reputation: 79298

scan(text=gsub('install.packages|["()]', '', input), what='')
Read 3 items
[1] "microbenchmark" "readxl"         "data.table"    

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76605

Maybe something like the following answers the question.

input <- 'install.packages("microbenchmark")
install.packages("readxl")
install.packages("data.table")'

input <- scan(text = input, what = character())
sub('^.*\\"(.*)\\".*$', '\\1', input)
#> [1] "microbenchmark" "readxl"         "data.table"

Created on 2022-04-21 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions