Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is plotly() and enquo + !! in conflict?

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

like image 298
Soph Carr Avatar asked Oct 31 '25 03:10

Soph Carr


2 Answers

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

enter image description here


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)
like image 122
akrun Avatar answered Nov 02 '25 17:11

akrun


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.

like image 31
Artem Sokolov Avatar answered Nov 02 '25 18:11

Artem Sokolov