Test for Prime Number in R (Example)

 

In this R programming tutorial you’ll learn how to identify prime numbers.

The article contains one example for the identification of prime numbers. To be more specific, the page will contain these contents:

Let’s start right away!

 

Creation of Example Data

Before all else, I’ll have to create some data that we can use in the examples later on:

x <- c(2, 7, 10, 17)          # Create example vector
x                             # Print example vector
# [1]  2  7 10 17

Have a look at the previous output of the RStudio console. It shows that our example data is a vector of four different integer values.

 

Example: Check for Prime Number Using isprime() Function of matlab Package

This example illustrates how to test whether a numerical value is a prime number using the R programming language.

For this, we first have to install and load the matlab package:

install.packages("matlab")    # Install & load matlab package
library("matlab")

In the next step, we can apply the isprime function of the matlab package as shown below. Note that we are wrapping the as.logical function around the isprime function to return a logical indicator instead of the values 0 or 1.

as.logical(isprime(x))        # Test for prime number
# [1]  TRUE  TRUE FALSE  TRUE

As you can see, the RStudio console has returned a vector of logicals. Each of these logicals corresponds to one of the elements in our input vector, and tells us whether a number is prime or not.

In the present example, we can see that 2, 7, and 17 are prime numbers, but 10 is not a prime number.

 

Video & Further Resources

Do you want to know more about the identification of prime numbers? Then you might have a look at the following video that I have published on my YouTube channel. I illustrate the R syntax of this page in the video.

 

 

In addition, you may read the other tutorials on my homepage:

 

Summary: In this article you have learned how to test for prime numbers in R programming. In case you have additional questions, let me know in the comments below.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top