How to divide every element in a list with each element in another list in R?

时间:2017-08-04 12:55:00

标签: r division

I am trying to check if all the elements of list A are divisible with all the elements of list B. if the remainder is 0 for all the elements, I want to print the corresponding elements of A.

my example code so far

first<-c(2,4,6,8,10,12)
second<-c(2,3)

for (i in first){
    for (j in second){
        if (i%%j==0){ #if any elements in first is divisible by all elements in second
            print(i)
            }
        }
    }

But it gives me output like this

[1] 2
[1] 4
[1] 6
[1] 6
[1] 8
[1] 10
[1] 12
[1] 12

I was expecting something [1] 6,12

3 个答案:

答案 0 :(得分:3)

We can use outer to get the modulus of each combination, and then rowSums to see which don't leave a remainder,

first[rowSums(outer(first, second, `%%`)) == 0]
#[1]  6 12

答案 1 :(得分:0)

Your code prints out all the numbers in first which are divisible by any number in second. Have a look at the all function, you are looking for something like

first<-c(2,4,6,8,10,12)
second<-c(2,3)

for (i in first){
    if (all(i %% second == 0)){ #if any elements in first is divisible by all elements in second
        print(i)
    }
}

答案 2 :(得分:0)

Oliver have right, to complete code you should do something like:

for (i in first){
  if(all(i%%second==0)){
    print(i)
  }
}