计算重复数量并将它们放在数据框的列中

时间:2017-07-01 03:28:32

标签: r count

我想计算一列中重复的数量,并将它们添加到另一列中。

例如,一些数据

a <- c(1,1,2,3,4,4)
b <- c("A","A","C","C","D","D")

df <- data.frame(a,b)

这是我要找的结果:

  a b count
1 1 A     1
2 1 A     2
3 2 C     1
4 3 C     1
5 4 D     1
6 4 D     2

4 个答案:

答案 0 :(得分:2)

{{1}}

答案 1 :(得分:1)

试试这个:

df$count <- with(df, ave(rep(1, nrow(df)), b, a, FUN = cumsum))

答案 2 :(得分:1)

我们可以使用data.table

执行此操作
library(data.table)
setDT(df)[, count := seq_len(.N), .(a, b)]
df
#    a b count
#1: 1 A     1
#2: 1 A     2
#3: 2 C     1
#4: 3 C     1
#5: 4 D     1
#6: 4 D     2

答案 3 :(得分:1)

我有一个类似的问题,但是只需要根据1列中的信息来计算重复项。 user7298145的答案对于较小的数据帧效果很好,但是我的数据有大约2万行,并因以下错误而失败:

Error: memory exhausted (limit reached?)
Error during wrapup: memory exhausted (limit reached?)

因此,我创建了一个实现此目的的for循环:

##  order the values that are duplicated
primary_duplicated <- primary_duplicated1[order(primary_duplicated1$md5), ]
##  create blank/NA column
primary_duplicated$count <- NA
##  set first value as 1
primary_duplicated$count[1] <- 1
##  set count of duplicates to 1 greater than the 
##  value of the preceding duplicate
for (i in 2:nrow(primary_duplicated)) {
      if (primary_duplicated$md5[i] == primary_duplicated$md5[i-1]) {
            primary_duplicated$count[i] <- primary_duplicated$count[i-1] + 1
      } else {
      ##  set the count value for the first incidence of
      ##  a duplicate as 1
            primary_duplicated$count[i] <- 1
      }
}