删除R中每个第n范围的行

huangapple go评论66阅读模式
英文:

how to delete every nth range of rows in R

问题

假设我有一个包含450行的数据框df。我想要删除从第10行到第18行的数据(即10, 11, 12, 13, 14, 15, 16, 17, 18)。然后类似地删除从第28行到第36行的数据,接着是46到54行的数据。依此类推,一直删除到从第442行到第450行的数据。

有什么建议吗,各位?

英文:

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?

答案1

得分: 3

创建一个`sequence`并移除这些行。第一个参数,`nvec`,是每个序列的长度(8,对每个序列都是重复的);第二个参数,`from`,是每个序列的起始点(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, ]

你也可以这样创建序列:
```r
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
# ...
英文:

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 &lt;- 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
# ...

huangapple
  • 本文由 发表于 2023年2月16日 19:13:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471443.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定