I am writing a function that uses plot_ly for a pieplot. The tilde (~) within argument labels = ~ is in conflict with the unquote operator !!. Is there a solution for this problem?
pieplotr <- function (df, Property){
Property_Name <- enquo(Property)
Pie <- plot_ly(df,
labels = ~!!Property_Name,
type = "pie")
return(Pie)
}
Toy_dataframe <- data.frame(
Sex = c("Male", "Female", "Female", "Male", "Male","NA"),
Height = c(12,11,7,3,9,NA),
Name = c("John", "Dora", "Dora","Dora", "Anna", "John"),
Last = c("Henry", "Paul", "House", "Houze", "Henry", "Bill"),
Location = c("Chicago", "Chicago", "Portland", "NYC", "NYC", "NYC"),
stringsAsFactors = TRUE)
e.g.
pieplotr(df = Toy_dataframe,
Property = Name)
I expect to return a pieplot, but I am getting the following error message:
Error in as.list.environment(x, all.names = TRUE) :
object 'Name' not found
We can evaluate after creating creating an expression
pieplotr <- function (df, Property){
Property_Name <- rlang::enquo(Property)
rlang::eval_tidy(
rlang::quo_squash(quo(
plot_ly(df, labels = ~!!Property_Name, type = "pie")
)))
}
pieplotr(df = Toy_dataframe, Property = Name)
-output

Or remove the ~!!
pieplotr <- function (df, Property){
Property_Name <- rlang::enquo(Property)
plot_ly(df, labels = Property_Name, type = "pie")
}
pieplotr(df = Toy_dataframe, Property = Name)
An alternative solution is to avoid non-standard-evaluation / quasiquoation entirely and simply modify how you are calling the function
pieplotr <- function (df, Property) {
plot_ly(df, labels = Property, type = "pie")
}
pieplotr( Toy_dataframe, ~Name ) # Notice the ~
The reason this works here is because the plotly universe uses formulas (defined via ~) to pass around information about variables. Tidyverse uses unevaluated expressions instead of formulas, which is the reason for needing enquo(), etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With