You can use the following methods to find the first row in a data frame in R that meets specific criteria:
Method 1: Find First Row that Meets One Criteria
#get first row where value in 'team' column is equal to 'B' df[which(df$team=='B', arr.ind=TRUE)[1],]
Method 2: Find First Row that Meets Multiple Criteria
#get first row where 'points' column > 15 and 'assists' column > 10 df[which(df$points>15 & df$assists>10, arr.ind = TRUE)[1],]
Method 3: Find First Row that Meets One of Several Criteria
#get first row where 'points' column > 15 or 'assists' column > 10 df[which(df$points>15 | df$assists>10, arr.ind = TRUE)[1],]
The following examples show how to use each method in practice with the following data frame in R:
#create data frame df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'), points=c(18, 13, 19, 14, 24, 21, 20, 28), assists=c(5, 7, 17, 9, 12, 9, 5, 12)) #view data frame df team points assists 1 A 18 5 2 A 13 7 3 A 19 17 4 B 14 9 5 B 24 12 6 C 21 9 7 C 20 5 8 C 28 12
Example 1: Find First Row that Meets One Criteria
We can use the following syntax to find the first row where the value in the team column is equal to ‘B’:
#find first row where team is equal to 'B' df[which(df$team=='B', arr.ind=TRUE)[1],] team points assists 4 B 14 9
We can see that the first row where the value in the team column is equal to ‘B’ is the fourth row of the data frame.
Example 2: Find First Row that Meets Multiple Criteria
We can use the following syntax to find the first row where the value in the points column is greater than 15 and the value in the assists column is greater than 10:
#find first row where points > 15 and assists > 10 df[which(df$points>15 & df$assists>10, arr.ind = TRUE)[1],] team points assists 3 A 19 17
We can see that the first row where the value in the points column is greater than 15 and the value in the assists column is greater than 10 is the third row of the data frame.
Example 3: Find First Row that Meets One of Several Criteria
We can use the following syntax to find the first row where the value in the points column is greater than 15 or the value in the assists column is greater than 10:
#find first row where points > 15 or assists > 10 df[which(df$points>15 | df$assists>10, arr.ind = TRUE)[1],] team points assists 1 A 18 5
We can see that the first row where the value in the points column is greater than 15 or the value in the assists column is greater than 10 is the first row of the data frame.
Note: The operators & and | represent “and” and “or” in R, respectively.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Find the Max Value in Each Row in R
How to Calculate the Median Value of Rows in R
How to Find Unique Rows Across Multiple Columns in R