EnlightenedFunky
EnlightenedFunky

Reputation: 325

New to functions in R

I am running this function in R that is supposed to plot the density curve on the histograms I have the original single code here:


ggplot(golf, aes(`Driving Accuracy`)) +
        geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
        stat_function(fun = dnorm, args = list(mean = mean(golf$`Driving Accuracy`, na.rm = T), 
                                               sd = sd(golf$`Driving Accuracy`, na.rm = T))) +
        xlab("Driving Accuracy (%)")

Now I was trying to modify this code, and use lapply, and my data which is numeric to do the similar plot(s).

plotter <- function(s) ggplot(Prediction.df, aes(s)) +
        geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
        stat_function(fun = dnorm, args = list(mean = mean(Prediction.df[,s], na.rm = T), 
                                               sd = sd(Prediction.df[,s], na.rm = T))) +
        xlab("Frequency")
lapply(X=names(Prediction.df),FUN=plotter)

The theory behind my attempt is that I saw that the initial dataframe was called golf, and in my case Predictions.df so I left that constant. Then I saw that column of interest was called so I replaced that with s in my new code, and function I believe that this is the mistake because the original code has golf$, as with mean and standard deviation. However, I did try Prediction.df$s and it did not work. Any thoughts?

Upvotes: 1

Views: 42

Answers (2)

akrun
akrun

Reputation: 886938

In the newer version of dplyr, passing a string in aes could be converted to symbol and evaluate (!!) as aes_string could be deprecated in the future. Note that ensym can take both quoted or unquoted argument

plotter <- function(s) {
           ggplot(Prediction.df, aes(!! rlang::ensym(s))) +
    geom_histogram(aes(y = ..density..),
        colour = "black", fill = "white") +
    stat_function(fun = dnorm, args = 
      list(mean = mean(Prediction.df[,s], na.rm = TRUE), 
             sd = sd(Prediction.df[,s], na.rm = TRUE))) +
    xlab("Frequency")
 }

or another option is .data[[s]] inside aes i.e. aes(.data[[s]])

Upvotes: 1

VitaminB16
VitaminB16

Reputation: 1234

aes() can't take a string input. Try aes_string() instead:

plotter <- function(s) ggplot(Prediction.df, aes_string(s)) +
        geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
        stat_function(fun = dnorm, args = list(mean = mean(Prediction.df[,s], na.rm = T), 
                                               sd = sd(Prediction.df[,s], na.rm = T))) +
        xlab("Frequency")
lapply(X=names(Prediction.df),FUN=plotter)

Upvotes: 2

Related Questions