在数据框中按组计数唯一/不同的值 [英] Counting unique / distinct values by group in a data frame

查看:76
本文介绍了在数据框中按组计数唯一/不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据框:

 > myvec 
name order_no
1 Amy 12
2 Jack 14
3 Jack 16
4 Dave 11
5 Amy 12
6 Jack 16
7汤姆19
8拉里22
9汤姆19
10戴夫11
11杰克17
12汤姆20
13艾米23
14 Jack 16

我想计算每个名称的不同order_no值的数量。应该产生以下结果:

  name number_of_distinct_orders 
Amy 2
杰克3
戴夫1
汤姆2
拉里1

我该怎么做? p>

解决方案

这应该是诀窍:

  ddply(myvec,〜name,summarize,number_of_distinct_orders = length(unique(order_no)))

这需要打包plyr。


Let's say I have the following 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

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

How can I do that?

解决方案

This should do the trick:

ddply(myvec,~name,summarise,number_of_distinct_orders=length(unique(order_no)))

This requires package plyr.

这篇关于在数据框中按组计数唯一/不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆