Subsetting a data frame based on a logical condition on a subset of rows

Viewed 941

I've tried to come up with a simple solution to the followig problem. Here is the minimum working example:

data <- data.frame(subject = c('Math', 'English', 'French', 'English'),
                   grade = c(1, 3, 5, 4))

I want a function that compares Enlish grades and returns a logical vector that has TRUE for the row with the highest english grade, and FALSE for all other rows. In this case [1] FALSE FALSE FALSE TRUE.

3 Answers

Another variation on a solution using the ifelse() command:

data <- data.frame(subject = c('Math', 'English', 'French', 'English'),
                   grade = c(1, 3, 5, 4))

output <-ifelse(data[,1] == "English" & data[,2] == 4, TRUE, FALSE)

> output
[1] FALSE FALSE FALSE  TRUE
Related