在数据框中按组计算唯一/不同的值 [英] Counting unique / distinct values by group in a data frame
本文介绍了在数据框中按组计算唯一/不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下数据框:
> myvec
name order_no
1 Amy 12
2 Jack 14
3 Jack 16
4 Dave 11
5 Amy 12
6 Jack 16
7 Tom 19
8 Larry 22
9 Tom 19
10 Dave 11
11 Jack 17
12 Tom 20
13 Amy 23
14 Jack 16
我想为每个 name
计算不同的 order_no
值的数量.它应该产生以下结果:
I want to count the number of distinct order_no
values for each name
. It should produce the following result:
name number_of_distinct_orders
Amy 2
Jack 3
Dave 1
Tom 2
Larry 1
我该怎么做?
推荐答案
这应该可以解决问题:
ddply(myvec,~name,summarise,number_of_distinct_orders=length(unique(order_no)))
这需要包plyr.
这篇关于在数据框中按组计算唯一/不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文