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
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.
CodePudding user response:
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")
CodePudding user response:
Another solution: you're repeating column names and arguments, so if you change your function to this, it works:
MaxLines <- function(df,col1,col2){
data.frame(df_col_1 = c(rep(df[[col1]][which.max(df[[col2]])], 2),
-Inf),
df_col_2 = c(-Inf, rep(max(df[[col2]]), 2)))
}
Output:
MaxLines(foo,'col_1','col_2')
# df_col_1 df_col_2
# 1 7 -Inf
# 2 7 3
# 3 -Inf 3