理想情况下,您应该先放入您尝试过的内容。我们可以帮助您调试。
无论如何,
> df = data.frame(N = c("A","B","A","A","D","M","K","T","T","K","T","E","F","E","G","G","V"), G = c(3,1,3,3,1,1,2,3,3,2,3,2,1,2,2,2,1))
> df
N G
1 A 3
2 B 1
3 A 3
4 A 3
5 D 1
6 M 1
7 K 2
8 T 3
9 T 3
10 K 2
11 T 3
12 E 2
13 F 1
14 E 2
15 G 2
16 G 2
17 V 1
> numberOfGroups = length(unique(df$G))
> numberOfGroups
[1] 3
> require(plyr)
> uniqueInGroup <- dlply(df,.fun=unique,.variables=.(G))
> uniqueInGroup
$`1`
N G
1 B 1
2 D 1
3 M 1
4 F 1
5 V 1
$`2`
N G
1 K 2
3 E 2
5 G 2
$`3`
N G
1 A 3
4 T 3
attr(,"split_type")
[1] "data.frame"
attr(,"split_labels")
G
1 1
2 2
3 3
lapply(uniqueInGroup, function(x) return(length(unique(x$N))))
哎呀,把第三个col分组了。改为使用第一个 col 运行此脚本,您将获得所需的输出。