事件组合的计数次数发生在数据帧列中 [英] Count number of times combination of events occurs in dataframe columns
本文介绍了事件组合的计数次数发生在数据帧列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如说我有
df< - data.frame('x'= c('a','a','b' ,'c','c','c'),
'y'= c('b','c','c','a','a','b'))
所以
xy
ab
ac
bc
ca
ca
ca
cb
a
和 b
一起出现(第一行), a
和 c
4次(行2,4,5,6)和 b
和 c
两次(第3和第7行),所以我想返回
xy num
ab 1
ac 4
bc 2
我希望这有道理吗?感谢提前
解决方案
这应该工作:
table(apply(df,1,function(x)paste(sort(x),collapse =' - ')))
ab ac bc
1 3 2
I have a data frame and I want to calculate the number of times each combination of events in two columns occur (in any order).
For example say I have
df <- data.frame('x' = c('a', 'a', 'b', 'c', 'c', 'c'),
'y' = c('b', 'c', 'c', 'a', 'a', 'b'))
So
x y
a b
a c
b c
c a
c a
c a
c b
a
and b
occur together once (1st row), a
and c
4 times (rows 2, 4, 5, 6) and b
and c
twice (3rd and 7th rows) so I would want to return
x-y num
a-b 1
a-c 4
b-c 2
I hope this makes sense? Thanks in advance
解决方案
This should work:
table(apply(df,1,function(x) paste(sort(x),collapse='-')))
a-b a-c b-c
1 3 2
这篇关于事件组合的计数次数发生在数据帧列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文