# Re: [R] Create a new var reflecting the order of subjects in existing var

From: Nguyen Dinh Nguyen <n.nguyen_at_garvan.org.au>
Date: Mon 02 Apr 2007 - 06:51:02 GMT

Followings are summary the solutions for my question. All the way to Roma!

But vote #1 for Jim, the simplest solution.

Thank you all of you for yours quick response

Regards

Nguyen

set.seed(123);dat <- data.frame(ID= c(rep(1,2),rep(2,3), rep(3,3), rep(4,4), rep(5,5)),

```                  var1 =rnorm(17, 35,2),

var2=runif(17,0,1))

```

# I would like to create a new var in dat which reflects the order of each
subject (ID), like this

# ID var1 var2 IDorder

##SOLUTIONS

# 1st (by Christos Hatzis)

y <- rle(dat\$ID) # rle: Run Length Endcoding

dat\$IDorder1 <- unlist(sapply(y\$lengths, FUN=function(x) seq(1,x)))

dat

dat\$IDorder2 <- unlist(tapply(dat\$ID,factor(dat\$ID), function(x)

1:length(x)),use.names=FALSE)

dat

#3rd (Jim Holtman)

dat\$IDorder3 <- ave(dat\$ID, dat\$ID, FUN=seq)

#4 (Gabor Grothendieck) Assuming the ID's are contiguous

dat <- transform(dat, IDorder3 = seq(ID) - match(ID, ID) + 1)

dat

#5th (Milton Cezar Ribeiro)

ID.freq<-table(dat\$ID)

ID.freq

ID.seq<-NULL

for (i in names(ID.freq))

{

ID.seq<-c(ID.seq,seq(from=1, to=ID.freq[i], by=1))

}

dat\$ID.seq<-ID.seq

dat

# END
[[alternative HTML version deleted]]

R-help@stat.math.ethz.ch 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. Received on Mon Apr 02 16:52:34 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 02 Apr 2007 - 16:30:35 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.