user3568106
user3568106

Reputation: 1

How to select n successive numbers with m numbers interval in r?

Here is a very simple question:

I have sequence of data: data <- 1:420

and I want to select data number 6,7,8 for every 12 numbers, so that I end up with a vector containing (6,7,8,18,19,20,30,31,32, ....,414,415,416)

Something like this (which does not work):

for (i in 0:34){new.data[i] <- (data[(12*i+6)],data[12*i+7],data[12*i+8])}

Hope someone has the simple solution, Martin

Upvotes: 0

Views: 62

Answers (1)

talat
talat

Reputation: 70296

Just create a logical vector of length 12 and use vector recycling:

test <- 1:420
idx <- rep(c(FALSE, TRUE, FALSE), c(5,3,4))
test[idx]
#  [1]   6   7   8  18  19  20  30  31  32  42  43  44  54  55  56  66  67  68  78  79  80  90  91  92 102 103 104 114 115 116 126 127 128 138
# [35] 139 140 150 151 152 162 163 164 174 175 176 186 187 188 198 199 200 210 211 212 222 223 224 234 235 236 246 247 248 258 259 260 270 271
# [69] 272 282 283 284 294 295 296 306 307 308 318 319 320 330 331 332 342 343 344 354 355 356 366 367 368 378 379 380 390 391 392 402 403 404
#[103] 414 415 416

Upvotes: 2

Related Questions