1

So I have a dataframe with a column with the following letter grades: C C A B

I would like to return the value A which is the highest score, but when I run the following code it shows an error (that doesn't happen when I put numerical values)

max(df$grades, na.rm=T)

Note: I already ordered the letter grades with the following code:

df$grades <- factor(df$grades)

Note: Here's the data I used:

class <- c(
  "blah1",
  "blah2",
  "blah4",
  "blah3"
)
grades <- c("C", "C", "A", "B")

df <- data.frame(class,grades)

Any help will be greatly appreciated!

the_dummy
  • 317
  • 1
  • 3
  • 15
  • Please provide your dataset or a subset of your dataset (e.g. using `dput`) so that problem is reproducible and we can try it out on our own machines... thus increasing the chance that someone will be able to give you a quick and good answer. Thanks :) – mysteRious Jul 15 '18 at 01:20
  • thank you for the tip @mysteRious :) ``` – the_dummy Jul 15 '18 at 01:23
  • See https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – mysteRious Jul 15 '18 at 01:26
  • `I would like to return the value A which is the highest score` how is that the highest score? – Ronak Shah Jul 15 '18 at 02:19
  • look at `ordered` function this will enable you use the `max` function: eg imagine the vector `x=c(3,12,6,9,4,1)` is arranged from smallest to biggest. Just think of `1` being the maximum, since it is the last. Now given another vector `y= c(4,6,9,12)` which is the maximum? you just do `max(ordered(y,levels=x))` and it will return 4, since 4 is the second last in x meaning second largest ie 2nd last in x after 1. – Onyambu Jul 15 '18 at 04:19

1 Answers1

0

Try dplyr with magrittr for the pipes:

library(dplyr)
library(magrittr)

And then just pipe your data frame to the arrange function:

> df %>% arrange(grades)
  class grades
1 blah4      A
2 blah3      B
3 blah1      C
4 blah2      C

Or you can choose only the A's (or whatever you like):

> df %>% arrange(grades) %>% filter(grades=="A")
  class grades
1 blah4      A

Or even pick out only the classes for those grades:

> df %>% arrange(grades) %>% filter(grades=="A") %>% select(class)
  class
1 blah4
mysteRious
  • 4,102
  • 2
  • 16
  • 36
  • Thanks for your response :) What should I do if I want to get the maximum, not look for "A"...? perhaps there are only B's and C's – the_dummy Jul 15 '18 at 01:34
  • You want to find out the top grade in the data frame? Try `df %>% arrange(grades) %>% slice(1) %>% select(grades)` -- the slice takes the top row, the select pulls only one variable. – mysteRious Jul 15 '18 at 01:39