Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove brackets and keep content inside from Data Frame

Tags:

regex

r

I have a dataframe pulled from a pdf that looks something like this

library(tidyverse)

Name <- c("A","B","A","A","B","B","C","C","C")
Result <- c("ND","[0.5]","1.2","ND","ND","[0.8]","ND","[1.1]","22")
 
results2 <- data.frame(Name, Result)
results2

I am trying to get rid of the brackets and have tried using gsub and a subsection and have failed. it looked like

results2$RESULT <-gsub("\\[","",results2$RESULT)

and resulted in an 'unexpected symbol' error message. I would like to get rid of the brackets and turn the Results into a numeric column.

like image 468
Cbotelho Avatar asked Feb 26 '26 14:02

Cbotelho


2 Answers

We may need to change it to add an OR (|) with ] so that both opening and closing square brackets are matched. Also, the column name is lower case. As R is case-sensitive, it wouldn't match the 'RESULT' which doesn't exist in the data

 gsub("\\[|\\]", "", results2$Result)
[1] "ND"  "0.5" "1.2" "ND"  "ND"  "0.8" "ND"  "1.1" "22" 
like image 91
akrun Avatar answered Mar 01 '26 03:03

akrun


As you are using library(tidyverse), you could do: regex is from akrun:

library(dplyr)
library(stringr)
results2 %>% 
  mutate(Result = str_replace_all(Result, "\\[|\\]", ""))
  Name Result
1    A     ND
2    B    0.5
3    A    1.2
4    A     ND
5    B     ND
6    B    0.8
7    C     ND
8    C    1.1
9    C     22
like image 29
TarJae Avatar answered Mar 01 '26 02:03

TarJae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!