Skip to content
Prev 323137 / 398502 Next

create unique ID for each group

Hi,
Try this:

dat1<- read.table(text="
ObsNumber???? ID????????? Weight
???? 1???????????????? 0001???????? 12
???? 2???????????????? 0001????????? 13
???? 3???????????????? 0001?????????? 14
???? 4????????????????? 0002???????? 16
????? 5???????????????? 0002???????? 17
???? 6?????????????????? N/A????????? 18?? 
???? 7?????????????????? 0003????????? 19
???? 8?????????????????? N/A?????????? 20
???? 9?????????????????? 0003????????? 21
",sep="",header=TRUE,colClass=c("numeric","character","numeric"),na.strings="N/A")
dat2<- read.table(text="
ID?????????????? Height
0001??????????? 3.2
0001???????????? 2.6
0001???????????? 3.2
0002???????????? 2.2
0002????????????? 2.6
",sep="",header=TRUE,colClass=c("character","numeric")) 

dat1[!is.na(dat1$ID),"UniqueID"]<-unlist(lapply(split(dat1,dat1$ID),function(x) with(x,as.character(interaction(ID,seq_len(nrow(x)),sep="_")))),use.names=FALSE) 

dat2$UniqueID<-unlist(lapply(split(dat2,dat2$ID),function(x) with(x,as.character(interaction(ID,seq_len(nrow(x)),sep="_")))),use.names=FALSE)
library(plyr)
join(dat1,dat2,by="UniqueID",type="left")
?# ObsNumber?? ID Weight UniqueID?? ID Height
#1???????? 1 0001???? 12?? 0001_1 0001??? 3.2
#2???????? 2 0001???? 13?? 0001_2 0001??? 2.6
#3???????? 3 0001???? 14?? 0001_3 0001??? 3.2
#4???????? 4 0002???? 16?? 0002_1 0002??? 2.2
#5???????? 5 0002???? 17?? 0002_2 0002??? 2.6
#6???????? 6 <NA>???? 18???? <NA> <NA>???? NA
#7???????? 7 0003???? 19?? 0003_1 <NA>???? NA
#8???????? 8 <NA>???? 20???? <NA> <NA>???? NA
#9???????? 9 0003???? 21?? 0003_2 <NA>???? NA
A.K.
Message-ID: <1367958357.15008.YahooMailNeo@web142605.mail.bf1.yahoo.com>
In-Reply-To: <CAAvu=bn9Jt4ioxTkPoxZHb24PUk2FCnGqLvmrTp-XLGWEDX1EA@mail.gmail.com>