'Convert string into vector
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]]
Solution 1:[1]
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)
Solution 2:[2]
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"
Solution 3:[3]
We can try
> scan(text = gsub("c\\((.*)\\)", "\\1", s), what = "", quiet = TRUE, sep = ",")
[1] "HJ229" " HJ230" " HJ231"
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 | |
| Solution 2 | |
| Solution 3 | ThomasIsCoding |
