[R] regular expression for nth character in a string

Jim Lemon jim at bitwrit.com.au
Mon Apr 25 12:36:15 CEST 2011


On 04/25/2011 08:17 PM, Gonçalo Ferraz wrote:
> Hi, I have a string
>
> "InTrouble"
>
> and want to extract, say, the first two characters: "In"
> or the last three: "blee"
> or the 3rd, 4th, and 5th: "Trou"
>
> Is there an easy way of doing this quickly with regular expressions in gsub, grep or similar?
>
Hi Gonçalo,
You could always try:

Im<-"InTrouble"
paste(unlist(strsplit(Im,""))[c(7,4,1,2,9,8,5,6,3)],collapse="")

Jim



More information about the R-help mailing list