Home > Mobile >  How to remove brackets and keep content inside from Data Frame
How to remove brackets and keep content inside from Data Frame

Time:10-07

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.

CodePudding user response:

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" 

CodePudding user response:

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
  • Related