计算变量 R 上的变量 [英] Count variable on a Variable R
本文介绍了计算变量 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
我尝试对它使用计数,但在将它用于不止一个变量时遇到了一些问题.
I tried to use count on it but had some issues to use it on more then just one variable.
推荐答案
with base R
With 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屋!
查看全文