[英]how add a column to a data.frame with the occurence number of an another column
I have the following data.frame 我有以下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
Not 100% sure but is this what you mean? 不确定100%,但这是您的意思吗?
> 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
Use sequence
and rle
on your sorted data.frame
: 使用sequence
和rle
您排序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. 我已经看过,但没有使用过ave
函数。 Looks like you can do this without reordering your original data.frame
: 看起来您可以执行此操作而无需重新排序原始data.frame
:
my.df$occ = ave(as.numeric(my.df$x), as.numeric(my.df$x), FUN=seq_along)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.