Select every nth row, offset the start and repeat

Viewed 1735

I am trying to create a new column in a data.frame that is created by selecting the 9th row of a column starting at the first row (i.e. row 1, row 9, row 17). Once it reaches the nth row of the column I need it to repeat this process starting at row 2 (selecting row 2, row 10, row 18). I have a fixed number of rows at 96 so I need it to repeat until it would start on the 9th row and then quit.

Here is an example of what I would like to do:

df <- data.frame(Row=1:96)
> df$nineth <- c(1,9,17,25,33,41,49,57,65,73,81,89,2,10,18,26,34,42,50,58,66,74,82,90)
> print(df)
   Row nineth
1    1      1
2    2      9
3    3     17
4    4     25
5    5     33
6    6     41
7    7     49
8    8     57
9    9     65
10  10     73
11  11     81
12  12     89
13  13      2
14  14     10
15  15     18
16  16     26
17  17     34
18  18     42
19  19     50
20  20     58
21  21     66
22  22     74
23  23     82
24  24     90

Is there a way to do this using a for loop? I am more familiar with them than the apply family.

2 Answers

You can use R's matrix/vector duality to do this easily...

df <- data.frame(Row=1:96)

df$nineth <- as.vector(matrix(df$Row, byrow = TRUE, ncol = 8))

head(df,15)
   Row nineth
1    1      1
2    2      9
3    3     17
4    4     25
5    5     33
6    6     41
7    7     49
8    8     57
9    9     65
10  10     73
11  11     81
12  12     89
13  13      2
14  14     10
15  15     18

Following works:

n <- 9
df$nineth <- unlist(lapply(1:(n-1), 
                           function(x){
                             df$Row[seq(x, nrow(df),by=n-1)]}))
Related