Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncate string from a certain character in R [duplicate]

Tags:

string

r

truncate

I have a list of strings in R which looks like:

WDN.TO
WDR.N
WDS.AX
WEC.AX
WEC.N
WED.TO

I want to get all the postfix of the strings starting from the character ".", the result should look like:

.TO
.N
.AX
.AX
.N
.TO

Anyone have any ideas?

like image 819
user802231 Avatar asked Jul 28 '11 15:07

user802231


Video Answer


2 Answers

Joshua's solution works fine. I'd use sub instead of gsub though. gsub is for substituting multiple occurrences of a pattern in a string - sub is for one occurrence. The pattern can be simplified a bit too:

> x <- c("WDN.TO","WDR.N","WDS.AX","WEC.AX","WEC.N","WED.TO")
> sub("^[^.]*", "", x)
[1] ".TO" ".N"  ".AX" ".AX" ".N"  ".TO"

...But if the strings are as regular as in the question, then simply stripping the first 3 characters should be enough:

> x <- c("WDN.TO","WDR.N","WDS.AX","WEC.AX","WEC.N","WED.TO")
> substring(x, 4)
[1] ".TO" ".N"  ".AX" ".AX" ".N"  ".TO"
like image 145
Tommy Avatar answered Sep 28 '22 08:09

Tommy


Using gsub:

x <- c("WDN.TO","WDS.N")
# replace everything from the start of the string to the "." with "."
gsub("^.*\\.",".",x)
# [1] ".TO" ".N" 

Using strsplit:

# strsplit returns a list; use sapply to get the 2nd obs of each list element
y <- sapply(strsplit(x,"\\."), `[`, 2)
# since we split on ".", we need to put it back
paste(".",y,sep="")
# [1] ".TO" ".N"
like image 43
Joshua Ulrich Avatar answered Sep 28 '22 09:09

Joshua Ulrich