Reputation: 851
I'm specifying a function to plot graphs like this:
func.plot <- function(z){
df %>%
ggplot(aes(z)) +
geom_histogram(aes(y =..density..),
binwidth = 0.004,
col="red",
fill="green",
alpha=.2) +
geom_density(col=2) +
labs(title="title", x="z", y="vertical axis")
}
The purpose is to produce histogram plots for a few variables in the data set, hence in this function I also want to use the variable names for the titles of the x
axis so as to make the plots differentiated. However, when calling the function with a variable such as func.plot(var)
there's an error saying:
Don't know how to automatically pick scale for object of type tbl_ts/tbl_df/tbl/data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (883): x
I've got a few questions:
For this specific function, how to fix it?
More generally, at times I want to write functions that refer to the argument in quotes, such as the x title above. Another simple example will be to read or write data like this:
func.write <- function(x){
write.csv(x, file="x.csv", row.names=FALSE)
}
This function is also not implemented properly when called out with func.write(df)
. It will write the data but under the name of "x.csv"
.
Upvotes: 3
Views: 2898
Reputation: 389135
Depending on how you want to pass the input arguments you can use one of the below function.
To pass quoted arguments :
library(ggplot2)
library(rlang)
func.plot_quoted <- function(df, z){
df %>%
ggplot(aes(!!sym(z))) +
geom_histogram(aes(y =..density..),
binwidth = 0.004,
col="red",
fill="green",
alpha=.2) +
geom_density(col=2) +
labs(title="title", x=z, y="vertical axis")
}
which can be used as
func.plot_quoted(mtcars, "cyl")
and to pass unquoted arguments
func.plot_unquoted <- function(df, z){
df %>%
ggplot(aes({{z}})) +
geom_histogram(aes(y =..density..),
binwidth = 0.004,
col="red",
fill="green",
alpha=.2) +
geom_density(col=2) +
labs(title="title", x={{z}}, y="vertical axis")
}
which can be used as
func.plot_unquoted(mtcars, cyl)
Upvotes: 6