How can I convert this string into a vector?
"c(HJ229, HJ230, HJ231)"
The desired result is "HJ229" "HJ230" "HJ231"
.
I have tried using stringr
, however the (
causes an issue because of regex.
t <- "c(HJ229, HJ230, HJ231)"
strsplit(str_remove(t, "c"), "(")[[1]]
CodePudding user response:
Another possible solution:
library(stringr)
s <-"c(HJ229, HJ230, HJ231)"
str_extract_all(s, "[A-Z]{2}\\d{3}")[[1]]
#> [1] "HJ229" "HJ230" "HJ231"
CodePudding user response:
Using base R
:
t = "c(HJ229, HJ230, HJ231)"
strsplit(gsub("[c()]", "", t), ", ")[[1]]
[1] "HJ229" "HJ230" "HJ231"
Using stringr
:
library(stringr)
str_split(str_remove_all(t, "[c()]"), ", ")[[1]]
[1] "HJ229" "HJ230" "HJ231"
CodePudding user response:
We can try
> scan(text = gsub("c\\((.*)\\)", "\\1", s), what = "", quiet = TRUE, sep = ",")
[1] "HJ229" " HJ230" " HJ231"
CodePudding user response:
You need to escape the parentheses to remove them with regex
using \\
and provide multiple patterns to match separated by |
(or).
library(stringr)
t <- "c(HJ229, HJ230, HJ231)"
str_split(str_remove_all(t, "c|\\(|\\)"), ", ")[[1]]
#> [1] "HJ229" "HJ230" "HJ231"
Created on 2022-02-25 by the reprex package (v2.0.1)