Reputation: 463
I have the following data.frame
x y
1 t1 5
2 t2 2
3 t2 7
4 t3 9
5 t1 6
how add a column with the occurence number of the value in the first column like below ?:
x y occ
1 t1 5 1
2 t2 2 1
3 t2 7 2
4 t3 9 1
5 t1 6 2
Upvotes: 1
Views: 261
Reputation: 193517
Use sequence
and rle
on your sorted data.frame
:
my.df <- data.frame(x=c("t1","t2","t2","t3","t1"), y=c(5,2,7,9,6))
# Order by x
my.df = my.df[order(my.df$x), ]
my.df$occ = sequence(rle(as.vector(my.df$x))$lengths)
my.df
# x y occ
# 1 t1 5 1
# 5 t1 6 2
# 2 t2 2 1
# 3 t2 7 2
# 4 t3 9 1
# Uncomment if you want to go back to original row order
# my.df[order(rownames(my.df)), ]
I had seen, but not used the ave
function. Looks like you can do this without reordering your original data.frame
:
my.df$occ = ave(as.numeric(my.df$x), as.numeric(my.df$x), FUN=seq_along)
Upvotes: 3
Reputation: 3894
Not 100% sure but is this what you mean?
> my.df <- data.frame(x=c("t1","t2","t2","t3","t1"), y=c(5,2,7,9,6))
> my.df <- data.frame(x=my.df$x,
+ y=my.df$y,
+ occ=sapply(1:nrow(my.df), function(i) sum(my.df$x[1:i] == my.df$x[i])))
> my.df
x y occ
1 t1 5 1
2 t2 2 1
3 t2 7 2
4 t3 9 1
5 t1 6 2
Upvotes: 3