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

问题描述 投票:1回答:4

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

例如,一些数据

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
r count
4个回答
1
投票

试试这个:

df$count = sequence(rle(df$a)$lengths)
df

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

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

1
投票

我遇到了类似的问题,但只需根据1列中的信息计算重复数。 user7298145的答案适用于小型数据框,但是我的数据有大约20k行并且因错误而失败:

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
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.