Open In App

Find the Nth highest value of a vector in R

Last Updated : 27 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to find the Nth largest value of a vector in the R Programming Language.

Steps for finding nth largest element in vector R:

Step 1: Create a vector and take input from the user.

Syntax : variable name = readline()

Where 

Variable is the valid identifier.

readline() will take input from user.

Step 2: Convert our data from string to int.

Syntax: variable 1= as.integer(variable2);

Where

Variable1 is the valid identifier which will store integer value of variable 2

Variable 2 is string which is needed to convert to integer. 

Step 3: Finding nth largest number using 

Syntax: sort(vector name ,True) [n value])

Where 

Vector name is the vector that we created.

Here True is used as we needed this vector in descending order.

N value is which the largest number you want to print.

Example 1:

In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and nth largest element.Here we are passing True as we need it in descending order. 

R




a<- c(1000,3000,4000)
 
x = readline();
 
# we are converting data from string to
# int and storing in x.
x = as.integer(x);
 
# we are sorting vector and printing
# nth element.As this vector is in sorted
# way we will get xth largest number
print(sort(a,TRUE)[x])


Output:

[1] 4000

Here user input is 1 so the output is 4000 as we need to find the first largest element.

Example 2: In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and yth the largest element.Here we are passing True as we need it in descending order. 

R




b<- c(1500, 334000, 33000)
 
# we are storing value given by user into y
y = readline();
 
# we are converting data from string to int and storing in y.
y = as.integer(y);
 
# we are sorting vector and printing yth element.
# As this vector is in sorted way(descending order)
# we will get yth largest number
print(sort(b,TRUE)[y])


Output:

[1] 33000

Here user input is 2 so the output is 33000 as we need to find the second largest element.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads