[英]r - dplyr: counting the frequency of unique values in one variable for each unique value of another variable in the same data frame
So here's a sample of some of the rows from my dataframe: 因此,这是我数据框中的一些行的示例:
> data[1:25, c("TR_DATE", "TR_TYPE...")]
TR_DATE TR_TYPE...
1 2016-03-01 4
2 2016-03-01 4
3 2016-03-01 5
4 2016-03-01 4
5 2016-03-01 1
6 2016-03-01 7
7 2016-03-01 4
8 2016-03-01 4
9 2016-03-01 24
10 2016-03-01 23
11 2016-03-01 4
12 2016-03-02 4
13 2016-03-02 1
14 2016-03-02 1
15 2016-03-02 4
16 2016-03-02 4
17 2016-03-02 14
18 2016-03-02 4
19 2016-03-02 4
20 2016-03-03 4
21 2016-03-03 1
22 2016-03-03 4
23 2016-03-03 23
24 2016-03-03 1
25 2016-03-03 4
What I'd like to do exactly is rearrange in such a way that for every unique day, I get the number of unique transaction types and the frequency of each transaction type 我想做的正是按照这样的方式重新安排:对于每一天,我都会得到唯一交易类型的数量以及每种交易类型的频率
Here's the code that I tried: 这是我尝试的代码:
data %>%
group_by(TR_DATE) %>%
summarise(trancount = n(), trantype = n_distinct(TR_TYPE...))
which gave me part of the result that I wanted: 这给了我想要的部分结果:
# A tibble: 68 x 3
TR_DATE trancount trantype
<date> <int> <int>
1 2016-03-01 5816 6
2 2016-03-02 5637 3
3 2016-03-03 4818 3
4 2016-03-04 5070 8
5 2016-03-05 4 2
6 2016-03-08 6707 5
7 2016-03-09 5228 5
8 2016-03-10 4722 6
9 2016-03-11 4469 8
10 2016-03-12 1 1
# ... with 58 more rows
so trantype tells me the number of unique transaction types that happened on a particular day, but I'd like to know the frequency of each of these unique transaction types. 因此trantype告诉我在特定日期发生的唯一交易类型的数量,但是我想知道每种独特交易类型的频率。 What would be the best way to go around doing this?
最好的方法是做什么? I tried looking around and found similar questions but was unable to modify the solutions to my requirement.
我尝试环顾四周,发现类似的问题,但无法修改解决方案以满足我的要求。 I'm fairly new to R and would really appreciate some help.
我对R相当陌生,非常感谢您的帮助。 Thanks.
谢谢。
You should group by both variables: 您应该按两个变量进行分组:
data %>%
group_by(TR_DATE, TR_TYPE...) %>%
summarise(trancount = n(), trantype = n_distinct(TR_TYPE...))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.