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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With