0

I'm trying to write a function that will return a data frame with two columns (the Date column, and a column of my choice), and one row (which has the max value in specified column of a data frame), to show me which date had the max value.

is_max <- function (month, col) {
    sub_row <- which.max(month$col)      #the row index of the max value
    A <- which(names(month) == col)      #the index of the desired column
    y <- month[sub_row, c(1, A)]
    return(y)
}

The result should be

     Date TOTAL
15 11-Aug    26

Instead, this gives the output

[1] Date  TOTAL
<0 rows> (or 0-length row.names)

When I work out each line of the function outside of the function body with the month and col data I want it works. Thanks for your help!

Jordan
  • 1
  • 1
    Not really enough information given, but try it with `month[[col]]` instead of `month$col`, assuming you are passing a character string to the `col` argument. `month$col` is likely returning `NULL` due to no column named `col`. – Rich Scriven Sep 08 '16 at 20:24
  • I would say there is no column defined as "col", to programmatically to refer to a column try: `which.max(month[[col]])` – Dave2e Sep 08 '16 at 20:27
  • Both answers are correct, it was the indexing method that needed correction. Thank you! – Jordan Sep 13 '16 at 14:26

0 Answers0