8 repetitive numeric values, as long as the df is

I need a column (y) added to my df, in which is repeated 8 times the "1", then 8 times the "2", then 8 times the "3", then 8 times the "4", etc.

It should be as long as the df is. See example output.

If the df does NOT have a length of a multiply of 8, the last repetitive numeric element does NOT have to be 8 times (see 3 times "5" in the example at the end).

Thank you.

> df1
   y
1  1
2  1
3  1
4  1
5  1
6  1
7  1
8  1
9  2
10 2
11 2
12 2
13 2
14 2
15 2
16 2
17 3
18 3
19 3
20 3
21 3
22 3
23 3
24 3
25 4
26 4
27 4
28 4
29 4
30 4
31 4
32 4
33 5
34 5
35 5

There may well be a more elegant solution and this might not cover every possible case.

#invent data
DF <- data.frame(id = 1:203)
#Calculate number of whole 64 member sequences
Full <- nrow(DF) %/% 64
FullSeq <- rep(rep(1:8, each=8), Full)
#Calculte remaining groups of eight
Eights <- (nrow(DF)-64*Full) %/% 8
if(Eights != 0) EightsSeq <- rep(1:Eights, each = 8) else EightsSeq <- numeric(0)
#Calculate last group with < 8 members
Remainder <- nrow(DF) - Full * 64 - Eights *8
RemainderSeq <- rep(Eights+1, Remainder)

Yseq <- c(FullSeq, EightsSeq, RemainderSeq)
DF$y <- Yseq
tail(DF,13)
#>      id y
#> 191 191 8
#> 192 192 8
#> 193 193 1
#> 194 194 1
#> 195 195 1
#> 196 196 1
#> 197 197 1
#> 198 198 1
#> 199 199 1
#> 200 200 1
#> 201 201 2
#> 202 202 2
#> 203 203 2

Created on 2023-04-13 with reprex v2.0.2

Dear FJCC,

I am amazed by people who get to apply such mathematics into a code. As a beginner in R with many years of experience in Excel, it is hard to get fealing of how to deal with such 'easy' repetations, where I would normally type the first part of the repetition in Excel and then just drag it down.

Although your code indeed works very well, I think I might have misargude my desired output.

In your code, after the final repetition of 8 times the value "8", it start again with 8 times the "1". While in fact, I would like it to continue with 8 times the "9", then 8 times the "10", then 8 times the "11", etc... till the end of the df.

And again: If the df does NOT have a length of a multiply of 8, the last repetitive numeric element does NOT have to be 8 times.

I had this idea

num_rep <- 8
DF <- data.frame(id = 1:203)
nr <- nrow(DF)
DF$col_frac_sum_round = floor(1+cumsum(c(0,rep(1/(num_rep),nr-1))))

DF
table(DF$col_frac_sum_round)
1 Like

@nirgrahamuk Thank you so much! It works and solves the final piece that I can not work out myself.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.