The glue function needs to refer to the data frame by a dollar sign in geom_brackets

56 views Asked by At

I have a code like this

#creating a categorical variable from a continuous one.
lobxx <- Loblolly %>% 
           mutate(ageG = if_else(age < 10,"A", if_else(age == 10, "B", if_else(age > 10, "C", "NA"))))
#calculating the t value
dfxx <- lobxx %>%
          rstatix::df_arrange(ageG,age) %>%
          rstatix::t_test(height~ageG) %>%
          rstatix::add_xy_position(x="ageG")
#creating a plot using ggplot and ggpubr::geom_bracket
dfxplotx <- ggplot(lobxx,aes(x= reorder(ageG,-height),y=height,fill=ageG))+
        stat_summary(geom="col",fun = mean)+
        ggpubr::geom_bracket(mapping=aes(xmin = group1, xmax = group2),data = dfxx,
                label = glue("P:{dfxx$p.adj}{dfxx$p.adj.signif}"),
                        y.position = c(53,60,53),
                        bracket.nudge.y = 5,inherit.aes = F)

dfxplotx

You can notice that I used the dollar sign to refer to the data frame. The point is that I noticed that most examples on the web did not use a format like this (data frame $ variable). Is there something wrong with the code or has something changed elsewhere? thank you.

I tried this code without using the $ sing in the glue function but I had error message. Why should this happen.

1

There are 1 answers

0
Nir Graham On BEST ANSWER

an alternative to $ syntax for pulling things out of lists is square brackets. When they both work there is no benefit to using one or the other apart from style/habit. However square bracket syntax is more general / powerful, as it can be used directly for metaprogramming; i.e. writing code which relies on the contents of variables to do one thing or another. Here is an example

myl <- list(x=1,y="a")

# direct access is just as good for one as another
# lets say we want the x contents from myl which is `1`
myl$x
myl["x"]
# but the square bracket took me 3 more keypresses to write

#if we want to write code with an additional level of `indirection`
# i.e. we didnt write code to get either x or y from myl
# we write code to get whatever of x or y another variable `get_me_` says to get 
get_me_<- "y"

# we can do this with square brackets
myl[get_me_]
# $y
# [1] "a"

# this is simply not a thing with $ syntax ; you would need to get into 
# parseing and evaluating string commands to force such an approach to work
myl$get_me_
# hence why square brackets are more 'powerful'