Select Rows if Value in One Column is Smaller Than in Another in R Dataframe
In this article, we will discuss how to select rows if the value in one column is smaller than another in dataframe in R programming language.
Data frame in use:
Method 1: Using Square Brackets
By using < operator inside the square bracket we can return the required rows.
Syntax:
dataframe[dataframe$column1 < dataframe$column2,]
where,
- dataframe is the input dataframe
- column1 is the first column
- column2 is the second column
Example: R program to select rows only if first column values is less than second column values
R
data= data.frame (sub1= c (100,89,90,78,98,93),
sub2= c (89,91,97,67,100,89))
print (data[data$sub1 < data$sub2,] )
print (data[data$sub2 < data$sub1,] )
|
Output:
Method 2 : Using subset() function
This function gets the subset of the data from the dataframe where the condition is specified.
Syntax:
subset(dataframe, column1<column2)
where,
- dataframe is the input dataframe
- column1 is the first column in the dataframe
- column2 is the second column in the dataframe
Example: R program to select rows where first column is less than column2
R
data= data.frame (sub1= c (100,89,90,78,98,93),
sub2= c (89,91,97,67,100,89))
print ( subset (data,sub1<sub2 ))
print ( subset (data,sub2<sub1))
|
Output:
Method 3 : Using filter() function
This function get the filtered data from the dataframe where the condition is specified. This is available in dplyr() package. So we need to install and load the package into the working space first.
Syntax:
filter(dataframe, column1<column2)
where,
- dataframe is the input dataframe
- column1 is the first column in the dataframe
- column2 is the second column in the dataframe
Example: R program to select rows where the first column is less than column2
R
library ( "dplyr" )
data= data.frame (sub1= c (100,89,90,78,98,93),
sub2= c (89,91,97,67,100,89))
print ( filter (data,sub1<sub2 ))
print ( filter (data,sub2<sub1))
|
Output:
Last Updated :
23 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...