2

I have this vector:

x <- c("a", " b", "c", "d", " e", "f")

There are spaces in x[c(2,5)]

How to delete the spaces to get all elements without spaces?, like this:

x <- c("a", "b", "c", "d", "e", "f")

Thanks

Sergio.pv
  • 1,330
  • 4
  • 14
  • 23

3 Answers3

3

You can use a gsub:

gsub(" ", "", x)

Note that this approach will remove any spaces in the elements of x, not only those at the beginning or end of each element.

talat
  • 66,143
  • 20
  • 123
  • 153
2

Try using

library(stringr)
str_trim(x)
akrun
  • 789,025
  • 32
  • 460
  • 575
2

Using gsub

gsub("^\\s+|\\s+$","",x)
agstudy
  • 116,828
  • 17
  • 186
  • 250