- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find numbers that are divisible by a certain number for a range of values in R?
In R, the divisibility of a number by a certain number can be found by using the modulus operator %%. If we want to check the divisibility of a set of numbers by a certain number then for loop will be used.
Check out the below given examples to understand how it can be done.
Example 1
To check which numbers between 1 and 100 are divisible by 10, use the following code −
for(x in 1:100){ + if(x%%10==0){ + print(x) + } + }
If you execute the above given code, it generates the following output −
[1] 10 [1] 20 [1] 30 [1] 40 [1] 50 [1] 60 [1] 70 [1] 80 [1] 90 [1] 100
Example 2
To check which numbers between 1 and 1000 are divisible by 50, use the code given below −
for(x in 1:1000){ + if(x%%50==0){ + print(x) + } + }
If you execute the above given code, it generates the following output −
[1] 50 [1] 100 [1] 150 [1] 200 [1] 250 [1] 300 [1] 350 [1] 400 [1] 450 [1] 500 [1] 550 [1] 600 [1] 650 [1] 700 [1] 750 [1] 800 [1] 850 [1] 900 [1] 950 [1] 1000
Example 3
To check which numbers between 1 and 100 are divisible by 4, use the code given below −
for(x in 1:100){ + if(x%%4==0){ + print(x) + } + }
If you execute the above given code, it generates the following output −
[1] 4 [1] 8 [1] 12 [1] 16 [1] 20 [1] 24 [1] 28 [1] 32 [1] 36 [1] 40 [1] 44 [1] 48 [1] 52 [1] 56 [1] 60 [1] 64 [1] 68 [1] 72 [1] 76 [1] 80 [1] 84 [1] 88 [1] 92 [1] 96 [1] 100