Jack_Carver
Jack_Carver

Reputation: 77

R - getting characters after symbol

Im thinkging how can I get characters after the symbol in my dataframe.

14990349-1293
3935033-31

The result should be

1293
31

I have created

substr(df$id,1,as.integer(gregexpr('-',df$id)-1))

But this returns characters BEFORE the symbol. I cant find a way how to get only that after symbol -

Upvotes: 1

Views: 533

Answers (3)

s_baldur
s_baldur

Reputation: 33488

sapply(strsplit(df$id, "-"), tail, 1)
 "1293" "31" 

Upvotes: 0

MKR
MKR

Reputation: 20085

Another way by extending OP's attempt to use substr/substring can be as:

substring(df$id,as.integer(gregexpr('-',df$id))+1) #Detect '-'.Then take all from right of it
#[1] "1293" "31" 

Data:

df <- data.frame(id = c("14990349-1293","3935033-31"), stringsAsFactors = FALSE)

Upvotes: 1

akrun
akrun

Reputation: 887028

We can use sub

as.numeric(sub(".*-", "", df$id))

Upvotes: 4

Related Questions