r - 如何计算 R 表中每一行的唯一值?

标签 r

我的表 g 是:

g
      ID     GROUP
1     123      A
2     656      A
3     456      A
4     123      A
5     456      B
6     789      A
7     453      B
8     123      C
9     720      D
10    456      E
11    453      A
12    863      F

我想知道有多少个唯一的 GROUP 与每个 ID 相关。


我想得到如下输出。 第 x 列应该给我一些独特的 GROUP

      ID       x
1    123       2      # as there are 2 unique GROUPs: A(twice) and C
2    453       2      # as it is B and A - 2 unique GROUPS
3    456       3      # as it is A, B, E
4    656       1      # as it is A
5    720       1      # as it is D
6    789       1      # as it is A
7    863       1      # as it is F

-------------------------------------------- ------------------------------

尝试解决上述问题的示例:

1.

agg<-aggregate(g$GROUP, by=list(ID=g$ID), unique)
agg
      ID        x
1    123     2, 6     # amount of digits in column x tells me how many GROUPs 
2    453     1, 2     # are related to single ID. 
3    456  2, 1, 4     # Numbers stand for: B  A  F  E  D  C
4    656        2                        # 1  2  3  4  5  6
5    720        5                       
6    789        2
7    863        3

agg$x
$`0`
[1] A C
Levels: B A F E D C
$`1`
[1] B A
...
...

2.

ggg <- aggregate(g$GROUP, by=list(ID=g$ID), paste, collapse=",")

     ID           x
1    123      A,A,C      # I want to count unique values (A,C)=2
2    453        B,A
3    456      A,B,E
4    656          A
5    720          D
6    789          A
7    863          F

最佳答案

table(unique(g)$ID)
#123 453 456 656 720 789 863 
#  2   2   3   1   1   1   1 

或者,

data.frame(table(unique(g)$ID))
#  Var1 Freq
#1  123    2
#2  453    2
#3  456    3
#4  656    1
#5  720    1
#6  789    1
#7  863    1

关于r - 如何计算 R 表中每一行的唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436418/

相关文章:

r - 与 HDF5 或 netCDF 相比,使用 .Rdata 文件有哪些缺点?

r - 中位数的函数类似于 "which.max"和 "which.min"/从data.frame中提取中位数行

r - 检查一个向量中的值是否小于另一向量(不同长度)中的值,并用 Y/N 答案填充表格

r - 在 Linux 中安装 Rserve 包

r - 定义在公式中使用的中缀运算符

r - 比较数组行

r - is.list 在 tibble 列上总是返回 true?

r - 具有position_stack的抖动文本/标签

R Markdown 文件: include help information

r - 如何判断一个数是否为正自然数?