R变换数据帧

时间:2017-03-13 14:28:56

标签: r dataframe

我有下表:

Account.Code    Brand       
1600    Sensodyne TP        
1600    Sensodyne TP        
1600    Zem     
1600    Sensodyne TP        
1800    Sensodyne TP        
1800    Burb MN     
1800    Burb MN     
2000    Lami        
2000    Lami        

如何转换为如下所示的表:

Account.Code    Brand   Count
1600    Sensodyne TP    3
1600    Zem             1
1800    Sensodyne TP    1
1800    Burb MN         2
2000    Lami            2

我需要做一个更大的数据集,只是一个简单的例子。

2 个答案:

答案 0 :(得分:0)

使用dplyr

library(dplyr)

df %>%
  group_by(Account.Code, Brand) %>%
    summarise(count = n())

#  Account.Code        Brand count
#         <int>       <fctr> <int>
#1         1600 Sensodyne_TP     3
#2         1600          Zem     1
#3         1800      Burb_MN     2
#4         1800 Sensodyne_TP     1
#5         2000         Lami     2

答案 1 :(得分:0)

或基础R解决方案

df$Count = 1
aggregate(Count ~ Account.Code + Brand, data=df, FUN=length)
  Account.Code        Brand Count
1         1800      Burb MN     2
2         2000         Lami     2
3         1600 Sensodyne TP     3
4         1800 Sensodyne TP     1
5         1600          Zem     1