[R] substring/strsplit question

Erik Iverson iverson at biostat.wisc.edu
Wed Oct 29 22:05:38 CET 2008


Upon re-reading your question, I did not provide what you wanted.

In your example, 'x' is a character vector that has three elements. 
Each element of 'x' has two or three characters.  Now I think I see what 
you want:

## untested, for the last character:
substr(x, nchar(x), nchar(x))

## untested, for the first character(s)
substr(x, 1, ifelse(nchar(x) == 3, 2, 1))

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
> 
>



More information about the R-help mailing list