Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How delete every 3rd Element of a vector?

Tags:

r

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.

like image 839
RedDragon2001 Avatar asked Sep 09 '21 22:09

RedDragon2001


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)]
like image 126
GuedesBF Avatar answered Nov 05 '22 19:11

GuedesBF


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
like image 28
akrun Avatar answered Nov 05 '22 20:11

akrun


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
like image 41
TarJae Avatar answered Nov 05 '22 20:11

TarJae