5

I want to remove everything before period (.) sign in the following string in R. I tried with gsub function.

Test <- c("Data.A", "Data.B", "Data.C", "Data.D")
gsub("[.]", "", Test)

Any help will be highly appreciated. Thanks

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
MYaseen208
  • 22,666
  • 37
  • 165
  • 309

2 Answers2

11

Try this: gsub("^.*\\.", "", Test)

What's it doing? Matches the beginning of the string with any character, any number of times. Then matches a single period. It replaces all of that with nothing.

> gsub("^.*\\.", "", Test)
[1] "A" "B" "C" "D"
Chase
  • 67,710
  • 18
  • 144
  • 161
7

Or if you find regular expressions abhorrent, you could use sapply and strsplit:

sapply(strsplit(Test,".",fixed = TRUE),"[[",2)
[1] "A" "B" "C" "D"

This is splitting each element on the '.' and then grabbing just the second element of the result from each.

joran
  • 169,992
  • 32
  • 429
  • 468