本文介绍了计算项目在多个列中的每一列中发生的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想阅读一个表,并创建另一个表,它可以计算多个特定列中唯一ID的次数。
I would like to read a table and create another table that counts how many times a unique ID occurs in multiple specific columns.
例如,我有一个表每一行显示交易,用户标识每个人的角色。
For example, I have a table where each row shows a transaction, with a userId identifying the role of each person.
buyer <- c("A", "A", "B", "A", "B", "C")
seller <- c("C", "B", "C", "B", "C", "A")
negotiator <- c("B", "C", "D", "D", "A", "B")
df <- data.frame(buyer, seller, negotiator)
df
# buyer seller negotiator
# 1 A C B
# 2 A B C
# 3 B C D
# 4 A B D
# 5 B C A
# 6 C A B
然后我会喜欢创建一个表,可以计算userId在交易中的角色数量。
I would then like to create a table that counts how many times a userId fulfilled a role in the transactions.
# id asBuyer asSeller asNegotiator
# A 3 1 1
# B 2 2 2
# C 1 3 1
# D 0 0 2
需要创建不同的数据框然后合并?
Would I need to create different dataframes and then merge?
推荐答案
列表例如
dd<-reshape2::melt(df,0)
xtabs(~value+variable,dd)
# variable
# value buyer seller negotiator
# A 3 1 1
# B 2 2 2
# C 1 3 1
# D 0 0 2
这篇关于计算项目在多个列中的每一列中发生的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!