变量R上的计数变量 [英] Count variable on a Variable R

查看:178
本文介绍了变量R上的计数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Tid <- c(1,1,2,2,2,3,4,4)
Uid <- c(10,10,11,11,12,13,10,14)

Data <- data.frame(Tid,Uid)

我想知道每个Tid上出现多少个不同的Uid。
我的结果应该是这样的。

I would like to know how many different Uid appear on every Tid. My Results should look something like this.

Tid, freqUid 
1, 1
2, 2
3, 1
4, 2

推荐答案

使用base R

as.data.frame(table(unique(Data)$Tid))
#   Var1 Freq
# 1    1    1
# 2    2    2
# 3    3    1
# 4    4    2

或(尽管列名称的信息量较少)

Or (though the column name is less informative)

aggregate(Uid ~ Tid, unique(Data), length)
#   Tid Uid
# 1   1   1
# 2   2   2
# 3   3   1
# 4   4   2






这里的基本思想是只对 Tid / Uid ,然后计算不同的 Tid 实例


The basic idea here is to only operate on the unique combinations of Tid/Uid and then count the different Tid instances

编辑:
每个@nicolas注释,我们也可以将 tapply 添加为可能的解决方案

per @nicolas comment, we can add tapply too here as a possible solution

as.data.frame.table(tapply(Data$Uid, Data$Tid, function(x) length(unique(x))))
#   Var1 Freq
# 1    1    1
# 2    2    2
# 3    3    1
# 4    4    2

这篇关于变量R上的计数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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