user3354212 user3354212 - 3 months ago 7
R Question

how to strisplit a vecter on a dot position reversely in r

I have a vector:

v <- c("1.1", "10.10", "11.11", "12.12", "13.1.13", "13.2.13", "14.14")


I would like to eliminate the behind part of the reverse first dot.
so my expected result is

c("1", "10", "11", "12", "13.1", "13.2", "14")

Answer

We can use sub to do this by matching the . (as . is a metacharacter specifying for any character element, we need to escape (\\) it to get the literal .) followed by one or more (+) elements that are not a dot ([^.]+) till the end of ($) the string and replace it with "".

sub("\\.[^.]+$", "", v)
#[1] "1"    "10"   "11"   "12"   "13.1" "13.2" "14"  
Comments