[R] Retain last grouping after a strsplit()

arun smartpink111 at yahoo.com
Tue Dec 11 20:31:18 CET 2012



HI,
You could also use:
x <- c("OYS-PIA2-FL-1",  "OYS-PIA2-LA-1",  "OYS-PI-LA-BB-1", "OYS-PIA2-LA-10")
gsub(".*\\-(\\d+)$","\\1",x)
#[1] "1"  "1"  "1"  "10"

#or 
gsub("[A-Z2-]","",x) #in this case
#[1] "1"  "1"  "1"  "10"



----- Original Message -----
From: Steven Ranney <steven.ranney at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, December 11, 2012 12:46 PM
Subject: [R] Retain last grouping after a strsplit()

All -

I have a column of SiteNames:

SiteName
OYS-PIA2-FL-1
OYS-PIA2-LA-1
OYS-PI-LA-BB-1
OYS-PIA2-LA-10
...
[truncated]

and I want to include only the last few digits into a new column.

I tried

substr(data$SiteName, 13, 20)

but because some SiteName values are of a different length, the final
hyphen (i.e., "-") was included:

"1"
"1"
"-1"
"10"
...

so I use

strsplit(data$SiteName, split = "-")

and get

"OYS" "PIA2" "FL" "1"
"OYS" "PIA2" "LA" "1"
"OYS" "PI" "LA" "BB" "1"
"OYS" "PIA2" "LA" "10"
...

which is great.  Unfortunately, I'm stuck.  I don't know how to
retrieve the final grouping of information from the strsplit()
statement I called into a new column.

Can you help?

Thanks -

SR
Steven H. Ranney

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.





More information about the R-help mailing list