How delete every 3rd Element of a vector?

Viewed 331

I have following vector:

myList = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

How can I remove EVERY 3rd element? (not like this: myList=myList[-3], myList=myList[-6],)

I need the following output:

1,2,4,5,7,8,10,11,13,14

I appreciate any help.

3 Answers

You can use a sequence as the index

myList[-c(3*1:5)]

[1]  1  2  4  5  7  8 10 11 13 14

You can use sequencing functions to make it consistent with any vector lengths with this:

myList[seq_along(myList)%%3!=0]

and this (credit to @thelatemail for that):

myList[-seq(3, length(myList), 3)]

You may also use a recycling logical vector:

myList[c(TRUE, TRUE, FALSE)]

-output:

[1]  1  2  4  5  7  8 10 11 13 14

We could first extract each third element and then remove:

myList1 <- myList[seq(0, length(myList), 3)]
myList[-myList1]
 [1]  1  2  4  5  7  8 10 11 13 14
Related