3

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 3

5

We can get the max 'grade' per 'subject' with ave compare it with the 'grade' to get a logical index and check whether the 'subject' is also 'English'

with(data, ave(grade, subject, FUN = max)==grade & subject == "English") 
#[1] FALSE FALSE FALSE  TRUE
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly! I didn't understand the subtleties of ave() until now.
2

Using an ifelse condition, one way would be the following.

library(dplyr)

data %>%
mutate(check = if_else(subject == "English" & grade == max(grade[subject == "English"]),
       TRUE,
       FALSE))

#  subject grade check
#1    Math     1 FALSE
#2 English     3 FALSE
#3  French     5 FALSE
#4 English     4  TRUE

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.