myfunc <- function(my_df,colmn) {
if (lapply(my_df[colmn], is.numeric) == TRUE){
print(class(my_df[colmn])) #Checking to see if I'm getting dataframe
print(colmn) #Check to see if I'm getting the right column
#Plotting a scatter plot
ggplot(data=my_df,
aes(x =my_df[colmn], #x-axis being the input colmn value via the function
y=my_df["colmn2"] # a column that is already present in the my_df dataframe
)
) +
geom_point(size=2)
}
}
myfunc(my_df=a_df, colmn="colmn1")
Output -
[1] "data.frame"
[1] "colmn1"
Error -
Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous. Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous. Error in is.finite(x) : default method not implemented for type 'list'
If I executed the ggplot outside of the function(below code), I get nice looking scatter plot without any error
ggplot(data=a_df, aes(x=a_df$colmn1,y=a_df$colmn2)) + geom_point(size=2)
I'm not sure why the values are defaulting to continous and why is.finite(x) coming up
EDIT - I tried x=col
, x=my_df$col
and x=my_df[col]
formats in aes()
aes_string()
,aes_string(x = colmn, y = "colmn2")
or use the.data
pronoun (using tidyeval from rlang),aes(x = .data[[colmn]], y = .data[["colmn2"]])
).aes_string()
is the "old way" of using ggplot2 in a function, and I believe it is now deprecated in favor of tidyeval. – aosmith