how to tidy a word separated by underscores in the character vector

Viewed 49

I have a very quick question on how to change the character vector below(1st to 2nd one)

data <- c("A_B", "A_C", "A _D", "D_ C", "C _C", "D_ D")
data <- c("A_B", "A_C", "A_D", "D_C", "C_C", "D_D") 

Thanks for your help!

2 Answers

[[:blank:]] works also in gsub to get rid of white space

data <- c("A_B", "A_C", "A _D", "D_ C", "C _C", "D_ D")


data2 <- sapply(data,gsub,pattern='[[:blank:]]',replacement='',USE.NAMES = F)

data2

output;

'A_B''A_C''A_D''D_C''C_C''D_D'

We could use gsub with a regex lookaround to remove one or more spaces (\\s+) that precedes or succeeds a _

gsub("\\s+(?=\\_)|(?<=_)\\s+", "", data, perl = TRUE)

-output

[1] "A_B" "A_C" "A_D" "D_C" "C_C" "D_D"

If the spaces are only present before or after the underscore, we can also do a non-specific matching of one or more spaces (if it is a single occurrence, sub is also enough)

gsub("\\s+", "", data)
[1] "A_B" "A_C" "A_D" "D_C" "C_C" "D_D"
Related