0

Can anyone help me in getting the right command to find the numbers which are divisible by 2 in and to get the elements in index positions within xVec? Please refer to the image below.

BTW, I used the View() command to check individually the items of my View(xVec) and (yVec), yet how can I find the numbers if I wanted them to be divisible by 2 under (xVec)? Should I use the command criteria.filter(xVec,/2) or just >str_detect(

RScriptVector

  • Pictures of data/code are not helpful on this site. It's much easier to help you if you include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that we can copy/paste into R to run and test. (See the link for tips on how to do just that). – MrFlick Aug 29 '18 at 18:29

1 Answers1

0

Welcome to R! In R, the binary operator %% computes the remainder of a division, and it's vectorized, just as most other binary operators in R. You can do this to get elements of a vector that are divisible by 2:

# The remainders
x_remainders <- xVec %% 2
# Get elements of xVec that is divisible by 2
x_div2 <- x[x_remainders == 0]
# Get indices within xVec where the element is divisible by 2
ind_x_div2 <- which(x_remainders == 0)

Hopefully this helps. str_detect may not be the best way to do it, since you are working with numbers rather than strings here.

Lambda Moses
  • 433
  • 5
  • 14