[R] split a string a keep the last part

Sarah Goslee sarah.goslee at gmail.com
Thu Aug 28 20:05:59 CEST 2014


Here's one way:

R> test<- 'AF14-485-502-89-00235'
R> test2 <- strsplit(test, "-")
R> test2
[[1]]
[1] "AF14"  "485"   "502"   "89"    "00235"

R> test2[[1]][length(test2[[1]])]
[1] "00235"

On Thu, Aug 28, 2014 at 1:41 PM, Jun Shen <jun.shen.ut at gmail.com> wrote:
> Hi everyone,
>
> I believe I am not the first one to have this problem but couldn't find a
> relevant thread on the list.
>
> Say I have a string (actually it is the whole column in a data frame) in a
> format like this:
>
> test<- 'AF14-485-502-89-00235'
>
> I would like to split the test string and keep the last part. I think I can
> do the following
>
> sub('.*-.*-.*-.*-(.*)','\\1', test)
>
> to keep the fifth part of the string. But this won't work if other strings
> have more or fewer parts separated by '-'. Is there a general way to do it?
> Thanks.
>
> Jun
>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list