In R how do I find whether an integer is divisible by a number?

前端 未结 4 2005
逝去的感伤
逝去的感伤 2021-01-13 06:45

Sorry for the inexperience, I\'m a beginning coder in R For example: If I were to make a FOR loop by chance and I have a collection of integers 1 to 100 (1:100), what would

相关标签:
4条回答
  • 2021-01-13 07:14
    for (x in 1:100) { 
      if (x%%5 == 0) {
        print(x)
      }
    }
    
    0 讨论(0)
  • 2021-01-13 07:15

    How's this?

    x <- 1:100
    div_5 <- function(x) x[x %% 5 == 0]
    div_5(x)
    
    0 讨论(0)
  • 2021-01-13 07:27

    The modulo operator %% is used to check for divisibility. Used in the expression x %% y, it will return 0 if y is divisible by x.

    In order to make your code work, you should include an if statement to evaluate to TRUE or FALSE and replace the y with 0 inside the curly braces as mentioned above:

    for (x in 1:100) { 
      if (x%%5 == 0) {
        print(x)
      }
    }
    

    For a more concise way to check for divisibility consider:

    for (x in 1:100) { 
      if (!(x%%5)){
        print(x)
      }
    }
    

    Where !(x %% 5) will return TRUE for 0 and FALSE for non-zero numbers.

    0 讨论(0)
  • 2021-01-13 07:28
    for (i in 1:10) 
    {
       if (i %% 2)
       {
          #some code
       }
    }
    
    0 讨论(0)
提交回复
热议问题