[R] substring/strsplit question

Marc Schwartz marc_schwartz at comcast.net
Wed Oct 29 22:11:07 CET 2008


on 10/29/2008 03:57 PM Erin Hodgess wrote:
> Dear R People:
> 
> Here is a toy example:
> 
>> x <- c("2E","5W","12H")
>> substr(x,2,2)
> [1] "E" "W" "2"
> 
> Sometimes x has 3 elements, sometimes 2.  I want to extract the last
> element, and then extract the other 1 or 2 elements.
> 
> How can I do this, please?
> 
> TIA,
> Sincerely,
> Erin


Hi Erin,

Is this what you want?


# Get the last character
> gsub(".*(.)$", "\\1", x)
[1] "E" "W" "H"


# Get the others
> gsub("(^.*).$", "\\1", x)
[1] "2"  "5"  "12"


See ?gsub

HTH,

Marc Schwartz



More information about the R-help mailing list