Rustam
Rustam

Reputation: 177

how to delete every nth range of rows in R

Suppose I have a dataframe df, which contains 450 rows. I want to delete rows from 10 through 18 (that is 10, 11, 12, 13, 14, 15, 16, 17, 18). Then similarly rows from 28 through 36, then 46:54. And so on, up to deleting rows from 442 through 450.

Any suggestions, guys?

Upvotes: 1

Views: 122

Answers (1)

Maël
Maël

Reputation: 52249

Create a sequence and remove those rows. The first argument, nvec, is the length of each sequence (8, repeated for each sequence); the second, from, is the starting point for each sequence (10, 28, ...).

n = 450
len = n %/% 18
s <- sequence(nvec = rep(9, len), from = seq(10, n, 18))
# [1]  10  11  12  13  14  15  16  17  18  28  29  30  31  32  33  34
# [17]  35  36  46  47  48  49  50  51  52  53  54  64  65  66  67  68
# [33]  69  70  71  72  82  83  84  85  86  87  88  89  90 100 101 102
# ...

your_df[-s, ]

You can also create the sequence like this:

rep(10:18, len) + rep(18*(0:(len - 1)), each = 9)
# [1]  10  11  12  13  14  15  16  17  18  28  29  30  31  32  33  34
# [17]  35  36  46  47  48  49  50  51  52  53  54  64  65  66  67  68
# [33]  69  70  71  72  82  83  84  85  86  87  88  89  90 100 101 102
# ...

Upvotes: 3

Related Questions