[R] Extract last 3 characters from numeric vector
Sarah Goslee
sarah.goslee at gmail.com
Sun Dec 4 16:36:16 CET 2011
You can use nchar() to get the length of the string, and use that in
substring:
mynum <- as.character(15.6)
> substring(mynum, nchar(mynum)-2, nchar(mynum))
[1] "5.6"
On Sun, Dec 4, 2011 at 8:38 AM, Kang Min <ngokangmin at gmail.com> wrote:
> Hi all,
>
> I have a numeric vector with 1 decimal place, and I'd like to extract
> the last 3 characters, including the decimal point. The vector ranges
> from 0 to 20.
>
> x <- round(runif(100)*20, digits=1)
>
> Some of numbers have 3 characters, and some have 4. I've read up on
> the substr() function but that extracts characters based on exact
> positions. How can I extract just the last 3 characters no matter the
> length of the number? e.g. from 16.7 I want 6.7, from 3.5 I want 3.5
> as it is.
>
> Thanks,
> Kang Min
>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list