我有以下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
答案 0 :(得分:3)
不是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
答案 1 :(得分:3)
在已排序的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)