0

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 (%)"

Example

Pasted example

camille
  • 16,432
  • 18
  • 38
  • 60
Tomas V
  • 23
  • 5
  • 1
    I've edited this but for operations involving only textual input and output it may be better to provide simple text. It will the question more accessible, especially for people using screen readers, etc. – Konrad Dec 18 '21 at 18:33

4 Answers4

1

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 (%)"  

data

v1 <- c("Sample_No ()", "SOC (%)")
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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 (%)"  
jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

Using gsub you could do:

header <- c("Sample_No ()", "SOC (%)")

gsub("\\s*\\(\\)", "", header)
#> [1] "Sample_No" "SOC (%)"
stefan
  • 90,330
  • 6
  • 25
  • 51
  • @TomasV You are welcome. But in my opinion akrun deserves the credit for the accepted answer. Not only was he the first to answer but also is his answer more complete than mine. – stefan Dec 18 '21 at 18:45
0

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.

Konrad
  • 17,740
  • 16
  • 106
  • 167