Home > Software engineering >  Removing elements that are multiples of 4 from a matrix in R
Removing elements that are multiples of 4 from a matrix in R

Time:10-06

This code is supposed to remove all mutiples of 4 from the given vector, when I run it, only 8 gets removed.

multipleoffour<- function(y){
y2<-y
for (n in y )
{if (n%%4==0)
y2<-y2[-n]
}
return (y2)  
}

multipleoffour(c(2,4,6,8,10,12,14))

CodePudding user response:

Since R is vectorized this is more of an R way to do this:

multipleoffour<- function(y){

    y[y %% 4 != 0]
}

multipleoffour(c(2,4,6,8,10,12,14))
## [1]  2  6 10 14

CodePudding user response:

The reason why your code doesn't work is because y2<-y2[-n] remove the nth element of the vector and not n itself. In your example it removed 8, which is the 4th element of your vector. Otherwise, I agree with other answers about how to do it more efficiently.

  •  Tags:  
  • r
  • Related