查找重复的行在R数据帧中重复的次数
我有一个如下示例所示的数据帧查找重复的行在R数据帧中重复的次数,r,R,我有一个如下示例所示的数据帧 a = c(1, 1, 1, 2, 2, 3, 4, 4) b = c(3.5, 3.5, 2.5, 2, 2, 1, 2.2, 7) df <-data.frame(a,b) 或 下面是使用函数ddply()从库plyr library(plyr) ddply(df,.(a,b),nrow) a b V1 1 1 2.5 1 2 1 3.5 2 3 2 2.0 2 4 3 1.0 1 5 4 2.2 1 6 4 7.0 1 你们可以
a = c(1, 1, 1, 2, 2, 3, 4, 4)
b = c(3.5, 3.5, 2.5, 2, 2, 1, 2.2, 7)
df <-data.frame(a,b)
或
下面是使用函数
ddply()
从库plyr
library(plyr)
ddply(df,.(a,b),nrow)
a b V1
1 1 2.5 1
2 1 3.5 2
3 2 2.0 2
4 3 1.0 1
5 4 2.2 1
6 4 7.0 1
你们可以一石二鸟:
aggregate(list(numdup=rep(1,nrow(df))), df, length)
# or even:
aggregate(numdup ~., data=transform(df,numdup=1), length)
# or even:
aggregate(cbind(df[0],numdup=1), df, length)
a b numdup
1 3 1.0 1
2 2 2.0 2
3 4 2.2 1
4 1 2.5 1
5 1 3.5 2
6 4 7.0 1
这里有两种方法
# a example data set that is not sorted
DF <-data.frame(replicate(sequence(1:3),n=2))
# example using similar idea to duplicated.data.frame
count.duplicates <- function(DF){
x <- do.call('paste', c(DF, sep = '\r'))
ox <- order(x)
rl <- rle(x[ox])
cbind(DF[ox[cumsum(rl$lengths)],,drop=FALSE],count = rl$lengths)
}
count.duplicates(DF)
# X1 X2 count
# 4 1 1 3
# 5 2 2 2
# 6 3 3 1
# a far simpler `data.table` approach
library(data.table)
count.dups <- function(DF){
DT <- data.table(DF)
DT[,.N, by = names(DT)]
}
count.dups(DF)
# X1 X2 N
# 1: 1 1 3
# 2: 2 2 2
# 3: 3 3 1
#未排序的示例数据集
DF使用dplyr:
summarise(group_by(df,a,b),length(b))
或
用nrow
@orizon替换function(x)nrow(x)
可以节省几个字符谢谢,更新了我的答案。是否可以用dplyr重新创建它?@maj我没有用过dplyr,所以无法回答是否有一个与a、b列无关的解决方案?(即,使用所有列)不要忘记管道!df%>%group_by(a,b)%%>%group_size()能否请您解释复制aggregate(list(numdup=rep(1,nrow(df)),df,length)
?@dukelover-aggregate需要将列相加为与分组变量相同的长度,因此我只需重复1即可获得此结果。非常感谢您的回复。你能解释一下这个代码吗?聚合(numdup~,数据=转换(df,numdup=1),长度)
以下是numdup~
的意义所在?
# a example data set that is not sorted
DF <-data.frame(replicate(sequence(1:3),n=2))
# example using similar idea to duplicated.data.frame
count.duplicates <- function(DF){
x <- do.call('paste', c(DF, sep = '\r'))
ox <- order(x)
rl <- rle(x[ox])
cbind(DF[ox[cumsum(rl$lengths)],,drop=FALSE],count = rl$lengths)
}
count.duplicates(DF)
# X1 X2 count
# 4 1 1 3
# 5 2 2 2
# 6 3 3 1
# a far simpler `data.table` approach
library(data.table)
count.dups <- function(DF){
DT <- data.table(DF)
DT[,.N, by = names(DT)]
}
count.dups(DF)
# X1 X2 N
# 1: 1 1 3
# 2: 2 2 2
# 3: 3 3 1
summarise(group_by(df,a,b),length(b))
group_size(group_by(df,a,b))
#[1] 1 2 2 1 1 1