gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:28:31 25 4
gpt4 key购买 nike

我的表 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com