'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?
Solution 1:[1]
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)
Solution 2:[2]
scan(text=gsub('install.packages|["()]', '', input), what='')
Read 3 items
[1] "microbenchmark" "readxl" "data.table"
Solution 3:[3]
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\")"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rui Barradas |
Solution 2 | onyambu |
Solution 3 | Uwe |