1
votes
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()

1
In the aes function, you don't need to repeat the dataframe name because it's already specified in the data= argument. Have you tried aes(x=colmn, ...)?Bill O'Brien
Try passing strings (without referring to the dataset) with 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
There are other question/answers out there that this is related to, but this one was the newest one I found searching "r ggplot2 in a function".aosmith

1 Answers

1
votes

Your problem is that the [] is not working within the aes() arguments

This should work:

MyData <- mtcars #Just to gain some reproducibility in the example. 

myfunc   <- function(my_df,colmn) {
 if (lapply(my_df[colmn], is.numeric) == TRUE){
   print(class(my_df[colmn])) 
   print(colmn) 

   #Create an additional object to store your variables
   DataTemp <- data.frame(my_df[colmn], my_df["mpg"])
   names(DataTemp) <- c("X", "Y")

#Plot the scatter plot using the created object
ggplot(data = DataTemp,
       aes(x = X, 
           y = Y )) +
  geom_point(size=2) }}

myfunc(my_df = MyData, colmn="gear")