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,380
  • 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
  • 68,970
  • 21
  • 126
  • 157
2

Try using

library(stringr)
str_trim(x)
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Using gsub

gsub("^\\s+|\\s+$","",x)
agstudy
  • 119,832
  • 17
  • 199
  • 261