我有以下data.frame
x y
1 t1 5
2 t2 2
3 t2 7
4 t3 9
5 t1 6
如何在第一列中添加具有值出现次数的列,如下所示?:
x y occ
1 t1 5 1
2 t2 2 1
3 t2 7 2
4 t3 9 1
5 t1 6 2
不是 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
在您的 sorted 上使用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)), ]
我见过,但没用过这个ave
功能。看起来您可以在不重新排序原始文件的情况下执行此操作data.frame
:
my.df$occ = ave(as.numeric(my.df$x), as.numeric(my.df$x), FUN=seq_along)