Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is causing "No non-missing arguments to max; returning -Inf"?

I have a function which will draw specific lines on my plot, defined as

MaxLines <- function(df,df_col_1,df_col_2){
  data.frame(df_col_1 = c(rep(df$df_col_1[which.max(df$df_col_2)], 2),
                                           -Inf), 
                       df_col_2 = c(-Inf, rep(max(df$df_col_2), 2)))
  
}

When I try to call this function I get the error mentioned in the title.

col_1 = c(5,6,7)
col_2 = c(1,2,3)
foo <- data.frame(col_1,col_2)
MaxLines(foo,col_1,col_2)


------------------------------------------------
new_1 new_2
1  -Inf  -Inf
2  -Inf  -Inf
3  -Inf  -Inf
Warning message:
In max(df$df_col_2) : no non-missing arguments to max; returning -Inf

I expect the function to return

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

col_1 col_2
7 -Inf
7 3
-Inf 3

But it does not. When inputting into the function directly ie.

MaxLines <- data.frame(col_1 = c(rep(foo$col_1[which.max(foo$col_2)], 2),
                                           -Inf), 
                       col_2 = c(-Inf, rep(max(foo$col_2), 2)))

I get the correct output, so it seems to just be the calling of the function.

>Solution :

Base R functions don’t easily allow you to pass in unquoted column names. You can either convert the symbols to strings

MaxLines <- function(df,df_col_1,df_col_2){
  df_col_1<-as.character(substitute(df_col_1))
  df_col_2<-as.character(substitute(df_col_2))
  data.frame(df_col_1 = c(rep(df[[df_col_1]][which.max(df[[df_col_2]])], 2),
                          -Inf), 
             df_col_2 = c(-Inf, rep(max(df[[df_col_2]]), 2)))
  
}
MaxLines(foo,col_1,col_2)

or you can pass in strings

MaxLines <- function(df,df_col_1,df_col_2){
  data.frame(df_col_1 = c(rep(df[[df_col_1]][which.max(df[[df_col_2]])], 2),
                          -Inf), 
             df_col_2 = c(-Inf, rep(max(df[[df_col_2]]), 2)))
  
}
MaxLines(foo,"col_1","col_2")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading