[R] Adding a column with a count of unique values
arun
smartpink111 at yahoo.com
Fri May 2 15:57:03 CEST 2014
Hi,
Try:
dat <- read.table(text="Person Time Change
2 0 3
2 10 5
2 15 7
3 0 4
3 5 2",sep="",header=TRUE)
dat1 <- transform(dat,Count= ave(rep(1,nrow(dat)), Person, FUN=cumsum))
#or
##If it is ordered by Person
dat2 <- transform(dat, Count= setNames(sequence(table(Person)),NULL))
#or
dat3 <- transform(dat,Count= ave(seq_along(Person), Person, FUN=seq_along))
all.equal(dat1,dat2)
#[1] TRUE
all.equal(dat1,dat3)
#[1] TRUE
A.K.
I have a dataframe that looks like this:
Person Time Change
2 0 3
2 10 5
2 15 7
3 0 4
3 5 2
I would like to add a column that counts each row for each person, like this:
Person Time Change Count
2 0 3 1
2 10 5 2
2 15 7 3
3 0 4 1
3 5 2 2
Thanks in advance!
More information about the R-help
mailing list