[英]R transform a data frame
I have table below: 我有下表:
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
How do I transform to table like below: 我如何转换为如下表:
Account.Code Brand Count
1600 Sensodyne TP 3
1600 Zem 1
1800 Sensodyne TP 1
1800 Burb MN 2
2000 Lami 2
I would need to do this a much larger data set, shown is just a simple example. 我将需要做一个更大的数据集,这只是一个简单的示例。
Using dplyr
: 使用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
Or a base R solution 或基本的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.