简体   繁体   English

如何在R中运行循环以找到7范围内的唯一数字组合?

[英]How to run a loop in R to find a unique combination of numbers within a range of 7?

I have a dataset which looks something like this:- 我有一个看起来像这样的数据集:

Key Days
A 1
A 2
A 3
A 8
A 9
A 36
A 37
B 14
B 15
B 44
B 45

I would like to split the individual keys based on the days in groups of 7. For eg:- 我想根据7天一组来分割各个密钥。例如:-

Key Days
A 1
A 2
A 3

Key Days
A 8
A 9

Key Days
A 36
A 37

Key Days
B 14
B 15

Key Days
B 44
B 45

I could use ifelse and specify buckets of 1-7, 7-14 etc until 63-70 (max possible value of days). 我可以使用ifelse并指定1-7、7-14等存储桶,直到63-70(天的最大可能值)。 However the issue lies with the days column. 但是,问题出在“天”列中。 There are lots of cases wherein there is an overlap in days - Take days 14-15 as an example which would fall into 2 brackets if split using the ifelse logic (7-14 & 15-21). 在很多情况下,几天之间存在重叠-以第14-15天为例,如果使用ifelse逻辑(7-14和15-21)进行划分,则会分成2个括号。 The ideal method of splitting this would be to identify a day and add 7 to it and check how many rows of data are actually falling under that category. 拆分此日期的理想方法是确定一天并将其添加7天,并检查实际上属于该类别的数据行数。 I think we need to use loops for this. 我认为我们需要为此使用循环。 I could do it in excel but i have 20000 rows of data for 2000 keys hence i'm using R. I would need a loop which checks each key value and for each key it further checks the value of days and buckets them in group of 7 by checking the first day value of each range. 我可以在excel中做到这一点,但我有20000个键的20000行数据,因此我使用R。我需要一个循环来检查每个键的值,并为每个键进一步检查day的值并将它们存储在7通过检查每个范围的第一天值。

We create a grouping variable by applying %/% on the 'Day' column and then split the dataset into a list based on that 'grp'. 我们通过在“天”列上应用%/%来创建分组变量,然后根据该“ grp”将数据集split为一个list

grp <- df$Day %/%7
split(df, factor(grp, levels = unique(grp)))
#$`0`
#  Key Days
#1   A    1
#2   A    2
#3   A    3

#$`1`
#  Key Days
#4   A    8
#5   A    9

#$`5`
#  Key Days
#6   A   36
#7   A   37

#$`2`
#  Key Days
#8   B   14
#9   B   15

#$`6`
#   Key Days
#10   B   44
#11   B   45

Update 更新资料

If we need to split by 'Key' also 如果我们也需要按“键”分开

lst <- split(df, list(factor(grp, levels = unique(grp)), df$Key), drop=TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM