I want to extract all the elements from a vector which are divisible by x or Y Again, I want to extract all the elements from a vector which are divisible by x and Y. Actually I want to extract the elements divided by 5 or 7, in one vector, 5 and 7 in another vector. Y<- X[X %% 5 == 0];Y, Y<- X[X %% 7 == 0];Y, it is working separately.
Asked
Active
Viewed 552 times
-1
-
Use `|` or `&` i.e. `(!(v1 %% 2))|(!(v1 %%3))` – akrun Nov 12 '19 at 22:00
-
1It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 12 '19 at 22:06
-
not working. Actually I want to extract the elements divided by 5 or 7, in one vector, 5 and 7 in another vector. Y<- X[X %% 5 == 0];Y, Y<- X[X %% 7 == 0];Y, it is working separately. – Roy Nov 12 '19 at 22:09
1 Answers
0
We can write a function to return a list of elements which are divisible by x
AND y
and x
OR y
.
get_all_elements <- function(vec, x, y) {
list(OR = vec[vec %% x == 0 | vec %% y == 0],
AND = vec[vec %% x == 0 & vec %% y == 0])
}
output <- get_all_elements(1:100, 5, 7)
output
#$OR
# [1] 5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50 55 56 60 63
# 65 70 75 77 80 84 85 90 91 95 98 100
#$AND
#[1] 35 70
get_all_elements(1:100, 7, 9)
#$OR
# [1] 7 9 14 18 21 27 28 35 36 42 45 49 54 56 63 70 72 77 81 84 90 91 98 99
#$AND
#[1] 63
You can extract two vectors separately if needed by output$OR
and output$AND
respectively.

Ronak Shah
- 377,200
- 20
- 156
- 213