[R] Extract part of a numer
arun
smartpink111 at yahoo.com
Tue Apr 23 21:13:26 CEST 2013
Hi,
Try this:
set.seed(25)
dat1<- data.frame(ID=c(10011001,10011004,20012001,2022001,12002),val=rnorm(5),stringsAsFactors=FALSE)
dat2<- dat1
library(stringr)
dat1$ID<-as.numeric(str_sub(dat1$ID,-4,-1))
dat1
# ID val
#1 1001 -0.2118336
#2 1004 -1.0415911
#3 2001 -1.1533076
#4 2001 0.3215315
#5 2002 -1.5001299
#or
dat2$ID<-as.numeric(gsub(".*(\\d{4})$","\\1",dat2$ID))
dat2
# ID val
#1 1001 -0.2118336
#2 1004 -1.0415911
#3 2001 -1.1533076
#4 2001 0.3215315
#5 2002 -1.5001299
A.K.
>Hi,
>
>How about a more complicated case (maybe simple to most of you :) )?
>
>10011001, 10011004, 20012001, 40012034, etc.,
>
>I would like to only keep the last 4 digits of each number.
>
>How should I do it?
>
>Thanks,
>
>York
>
>----- Original Message -----
>From: arun <smartpink111 at yahoo.com>
>To: R help <r-help at r-project.org>
>Cc:
>Sent: Tuesday, April 23, 2013 12:10 PM
>Subject: Re: Extract part of a numer
>
>Hi,
>May be this helps:
>set.seed(25)
>dat1<- data.frame(ID=c("1001#01","1001#02","1001#03","1002#01","1002#02"),val=rnorm(5),stringsAsFactors=FALSE)
>dat1$ID<-as.numeric(gsub("#.*","",dat1$ID))
>dat1
># ID val
>#1 1001 -0.2118336
>#2 1001 -1.0415911
>#3 1001 -1.1533076
>#4 1002 0.3215315
>#5 1002 -1.5001299
>A.K.
>
>
>Hi all,
>
>I have a database with a colume ID have the ID numbers like this1001#01, 1001#02, etc..
>
>How could I do to just extract 1001 out?
>
>Thanks,
>
>York
More information about the R-help
mailing list