I am working with some headers and I need to remove parenthesis in the headers but only where is nothing inside but to keep the others if it has the unit of measure. e.g.
"Sample_No ()" - Sample_No
"SOC (%)" - "SOC (%)"
I am working with some headers and I need to remove parenthesis in the headers but only where is nothing inside but to keep the others if it has the unit of measure. e.g.
"Sample_No ()" - Sample_No
"SOC (%)" - "SOC (%)"
If it is empty parentheses match the open parentheses followed by the closing parentheses without any other characters and replace with blank (""
) in gsub
(if there is a chance of more than one matches) or with the example even sub
is enough)
gsub("\\s*\\(\\)", "", v1)
-output
[1] "Sample_No" "SOC (%)"
Or use str_remove
from stringr
library(stringr)
trimws(str_remove_all(v1, fixed("()")))
[1] "Sample_No" "SOC (%)"
v1 <- c("Sample_No ()", "SOC (%)")
Using gsub
with a regular expression. \\s
denotes whitespace \\(
and \\)
the parentheses that have to be escaped.
x <- c("Sample_No ()", "Sample_No", "SOC (%)", "SOC (%)")
gsub('\\s\\(\\)', '', x)
# [1] "Sample_No" "Sample_No" "SOC (%)" "SOC (%)"
Using gsub
you could do:
header <- c("Sample_No ()", "SOC (%)")
gsub("\\s*\\(\\)", "", header)
#> [1] "Sample_No" "SOC (%)"
For completeness, you may wan to explore the stringi
package. The code below also trims potential empty spaces that may be left after the operation.
vecA <- c("Sample_No ()", "SOC (%)")
stringi::stri_trim_both(
stringi::stri_replace_all(str = vecA, replacement = "", fixed = "()")
)
# [1] "Sample_No" "SOC (%)"
This particular operation is trivial, but stringi
comes in handy for more complex operations.