0 votes
1 view
in R Programming by (5k points)
recategorized by

So " xx yy 11 22  33 " will become "xxyy112233". How can I achieve this?

1 Answer

0 votes
by (23.2k points)

You can use the following functions to remove all whitespaces from a string:

Using gsub from the base package:

Here,

fixed

logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments.

For example:

whitespace <- " xx yy 11 22  33 "

x <- c(

  " x y ", 

  whitespace,

  paste0(whitespace,"x",whitespace,"y",whitespace, collapse = ""),   

  NA  

)

 x

[1] " x y "                                                

[2] " xx yy 11 22  33 "                                    

[3] " xx yy 11 22  33 x xx yy 11 22  33 y xx yy 11 22  33 "

[4] NA                

 gsub(" ", "", x, fixed = TRUE)

[1] "xy"                               "xxyy112233"                      

[3] "xxyy112233xxxyy112233yxxyy112233" NA          

You can also use the stringr package as follows:

library(stringr)

 str_replace_all(x, fixed(" "), "")

[1] "xy"                               "xxyy112233"                      

[3] "xxyy112233xxxyy112233yxxyy112233" NA 

...