[英]Group dataframe by multiple variables in R
I have a dataframe containing 5713 rows and 7 columns. 我有一个包含5713行和7列的数据框。 Many of the rows are duplicates. 许多行是重复的。 I need to create groups of 5 by "gender" and "size" while ensuring the "item" column does not contain duplicates and the "type" column only contains a maximum of 1 "Fleece". 我需要按“性别”和“大小”创建5个组,同时确保“项目”列不包含重复项,并且“类型”列仅包含最多1个“抓绒”。 I have tried sample, split, group_by, sample_n, but can't seem to figure out how to include all the variables. 我尝试了sample,split,group_by,sample_n,但似乎无法弄清楚如何包括所有变量。
Here is a sample of the dataframe: 这是数据框的示例:
SKU UPC type rating size gender item
1 M3MEN-SU15-BLU-XXL 628012010215 Tee 5 XXL M M3MEN
2 M3MEN-SU15-GRY-XXL 628012010314 Tee 5 XXL M M3MEN
3 M3MEN-SU15-GRY-XL 628012010316 Tank 5 XL M M3MEN
4 MAMA-CHA-S *MAMA-CHA-S* Tank 5 S M MAMA
5 MAMA-CHA-S *MAMA-CHA-S* Tee 5 S M MAMA
6 MBAN-CHA-M *MBAN-CHA-M* Fleece 3 M W MBAN
7 WAZA-CHA-L *WAZA-CHA-L* Fleece 3 L M WAZA
8 MBAN-CHA-M *MBAN-CHA-M* Fleece 3 M W MBAN
9 MBAN-CHA-M *MBAN-CHA-M* Fleece 3 M M MBAN
10 MCON-CHA-M *MCON-CHA-M* Fleece 3 M M MCON
Ideally I would like to create a new column that creates a unique ID for each group of 5. 理想情况下,我想创建一个新列,为每组5组创建一个唯一ID。
For example: 例如:
SKU UPC type rating size gender item id
1 M3MEN-SU15-BLU-S 628012010215 Tee 5 S M M3MEN 1
2 MAMA-CHA-S *MAMA-CHA-S* Tank 5 S M MAMA 1
3 MBAN-CHA-S *MBAN-CHA-S* Tank 3 S M MBAN 1
4 MAZA-CHA-S *MAZA-CHA-S* Tee 3 S M MAZA 1
5 MCON-CHA-S *MCON-CHA-S* Fleece 3 S M MCON 1
6 W3MEN-SU15-BLU-M 428012010215 Tee 2 M W W3WOM 2
7 WAMA-CHA-M *WAMA-CHA-M* Tank 4 M W MAMA 2
8 WBAN-CHA-M *WBAN-CHA-M* Tank 5 M W MBAN 2
9 WAZA-CHA-M *WAZA-CHA-M* Tee 1 M W MAZA 2
10 WCON-CHA-M *WCON-CHA-M* Fleece 3 M W MCON 2
I have been struggling with this for awhile now. 我已经为此苦了一段时间了。 Any help would be greatly appreciated! 任何帮助将不胜感激!
Avoiding duplicates of item
within a group is straightforward with the distinct
function: 通过distinct
功能,避免在组内重复item
很简单:
library(dplyr)
df %>%
group_by(gender, size) %>%
distinct(item)
Ensuring there is not more than one "Fleece" is a bit trickier, but doable with filter
and cumsum
. 确保不多于一个“ Fleece”比较棘手,但是可以使用filter
和cumsum
。 This removes all but the first Fleece (within each group). 这将删除除第一个羊毛外的所有羊毛(在每个组中)。
filter(!(type == "Fleece" & cumsum(type == "Fleece") > 1))
Then you can do sample_n
as you attempted originally: 然后,您可以像最初尝试的那样执行sample_n
:
sample_n(5)
In total, your code is: 总的来说,您的代码是:
df <- df %>%
group_by(gender, size) %>%
distinct(item) %>%
filter(cumsum(type == "Fleece") <= 1) %>%
sample_n(5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.