Reputation: 23898
I want to remove parentheses and brackets from a string. I got the required result, however looking for more compact method.
Test <- c("-0.158)", "0.426)", "1.01)", "1.6)", "2.18)", "2.77]")
stringr::str_replace(
string = Test
, pattern = "\\)"
, replacement = ""
)
# [1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77]"
stringr::str_replace(
string = Test
, pattern = "\\]"
, replacement = ""
)
# [1] "-0.158)" "0.426)" "1.01)" "1.6)" "2.18)" "2.77"
stringr::str_replace(
string = stringr::str_replace(
string = Test
, pattern = "\\]"
, replacement = ""
)
, pattern = "\\)"
, replacement = ""
)
# [1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
Wonder if it can be obtained with a single command something like this
stringr::str_replace(
string = Test
, pattern = "\\)^]"
, replacement = ""
)
Edited
Found a very simple solution
readr::parse_number(Test)
[1] -0.158 0.426 1.010 1.600 2.180 2.770.
Upvotes: 2
Views: 4885
Reputation: 886948
We can use |
gsub("\\)|\\]", "", Test)
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
or instead of escaping place the brackets inside the []
gsub("[][()]", "", Test)
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
If we want to do the extract instead of removing use either gregexpr/regmatches
from base R
or str_extract
from stringr
to check for patterns where a number could start with -
and include .
library(stringr)
str_extract(Test, "-?[0-9.]+")
#[1] "-0.158" "0.426" "1.01" "1.6" "2.18" "2.77"
Upvotes: 4