Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R数据帧筛选器和计数唯一项_R_Dataframe - Fatal编程技术网

R数据帧筛选器和计数唯一项

R数据帧筛选器和计数唯一项,r,dataframe,R,Dataframe,假设我有一个数据帧,例如: A B C D 1 1 1 1 1 1 1 1 2 2 1 2 2 2 2 2 2 2 1 2 我想创建一个数据帧,它只包含唯一的条目和它发生的次数。比如说: A B C D count 1 1 1 1 2 2 2 1 2 2 2 2 2

假设我有一个数据帧,例如:

A    B    C    D  
1    1    1    1  
1    1    1    1  
2    2    1    2  
2    2    2    2  
2    2    1    2  
我想创建一个数据帧,它只包含唯一的条目和它发生的次数。比如说:

A    B    C    D    count
1    1    1    1     2  
2    2    1    2     2   
2    2    2    2     1  
我该怎么做?

您可以尝试使用“data.table”包,如下所示:

> library(data.table)
> as.data.table(dat)[, .N, by = names(dat)]
   A B C D N
1: 1 1 1 1 2
2: 2 2 1 2 2
3: 2 2 2 2 1
或与“dplyr”类似:


一个
base R
选项是

aggregate(cbind(Count=1:nrow(df1))~., df1, FUN=length)
#    A B C D Count
#  1 1 1 1 1     2
#  2 2 2 1 2     2
#  3 2 2 2 2     1
或者@David Arenburg建议的修改

aggregate(Count ~ ., cbind(Count = 1, df1), FUN=length)

有趣的方法。以前从未见过这种情况。请注意,添加的列
Count
的值未在聚合中使用。是的,我看到了我的基本方法是将
rownames
aggregate
一起使用,或者使用
unique(cbind(dat,Count=ave(rep(1,nrow(dat)),dat,FUN=length))
。是的,可能是
聚合(Count~,cbind(Count=1,df1),length)
会更具可读性吗?太棒了!非常感谢。您让我不用无意识地查找每个级别组合的长度。
aggregate(Count ~ ., cbind(Count = 1, df1), FUN=length)