How to remove one row of column labels in a gt table? - r

#Preparing the data and loading packages
library(modelsummary);library(tidyverse);library(gt)
as_tibble(mtcars)
df <- mtcars %>% mutate(cyl_ = factor(cyl)) %>%
dplyr::select(cyl_, mpg, vs, am, hp, wt)
#Gets table of descriptive statistics about different subsets of the data
print(t1 <- datasummary_balance(~cyl_,
data = df,
output = "gt"))
#This hides the "Std. Dev." columns
t1 %>% cols_hide(c(3,5,7))
#Now I want to hide the "Mean" column labels, but I want to keep the "cyl_" value column labels. Any ideas how?
I want something like this:

Using the gt package, you can pipe your table to tab_options(column_labels.hidden = TRUE) to remove column labels. Unfortunately, this will remove both levels: the column headers, and the spanning labels that include the cyl info you want to keep.
Note that datasummary_balance() produces a highly customized table which is intended to be used as a ready-made output. In cases like these, it might be easier to just build the custom table you want using datasummary() instead of trying to customize datasummary_balance() (square peg, round hole, etc). For example:
library(modelsummary)
library(tidyverse)
df <- mtcars %>%
select(cyl, mpg, vs, am, hp, wt) %>%
mutate(cyl = factor(sprintf("%s (N = %s)", cyl, n()))) %>%
as.data.frame() # The `All()` function does not accept tibbles
datasummary(
All(df) ~ Mean * cyl,
data = df,
output = "gt")

Related

ggplot2: Can you acess the .data argument in subsequent layers?

I have multiple graphs I'm generating with a data set. I preform many operations on the data (filtering rows, aggregating rows, calculations over columns, etc.) before passing on the result to ggplot(). I want to access the data I passed on to ggplot() in subsequent ggplot layers and facets so I can have more control over the resulting graph and to include some characteristics of the data in the plot itself, like for example the number of observations.
Here is a reproducible example:
library(tidyverse)
cars <- mtcars
# Normal scatter plot
cars %>%
filter(
# Many complicated operations
) %>%
group_by(
# More complicated operations
across()
) %>%
summarise(
# Even more complicated operations
n = n()
) %>%
ggplot(aes(x = mpg, y = qsec)) +
geom_point() +
# Join the dots but only if mpg < 20
geom_line(data = .data %>% filter(mpg < 20)) +
# Include the total number of observations in the graph
labs(caption = paste("N. obs =", NROW(.data)))
one could of course create a a separate data set before passing that onto ggplot and then reference that data set throughout (as in the example bellow). However, this is much more cumbersome as you need to save (and later remove) a data set for each graph and run two separate commands for just one graph.
I want to know if there is something that can be done that's more akin to the first example using .data (which obviously doesn't actually work).
library(tidyverse)
cars <- mtcars
tmp <- cars %>%
filter(
# Many complicated operations
) %>%
group_by(
# More complicated operations
across()
) %>%
summarise(
# Even more complicated operations
n = n()
)
tmp %>%
ggplot(aes(x = mpg, y = qsec)) +
geom_point() +
# Join the dots but only if mpg < 20
geom_line(data = tmp %>% filter(mpg < 20)) +
# Include the total number of observations in the graph
labs(caption = paste("N. obs =", NROW(tmp)))
Thanks for your help!
In the help page for each geom_ it helpfully gives a standard way:
A function will be called with a single argument, the plot data. The return value must be a data.frame, and will be used as the layer data. A function can be created from a formula (e.g. ~ head(.x, 10)).
For labs on the other hand you can use the . placeholders in piping, but you have to a) give the . as the data argument in the first place and b) wrap the whole thing in curly braces to recognise the later ..
So for example:
library(tidyverse)
cars <- mtcars
# Normal scatter plot
cars %>%
filter() %>%
group_by(across()) %>%
summarise(n = n()) %>%
{
ggplot(., aes(x = mpg, y = qsec)) +
geom_point() +
geom_line(data = ~ filter(.x, mpg < 20)) +
labs(caption = paste("N. obs =", NROW(.)))
}
Or if you don't like the purrr formula syntax, then the flashy new R anonymous functions work too:
geom_line(data = \(x) filter(x, mpg < 20)) +
Unfortunately the labs function doesn't seem to have an explicit way of testing whether data is shuffling invisibly through the ggplot stack as by-and-large it usually can get on with its job without touching the main data. These are some ways around this.

Applying subgrouping to a subgroup in R

I have this code to create two subset columns based on quantiles, one column for median split and one column for quartile split.
mtcars <- subset(mtcars, select = c("cyl", "disp"))
mtcars$median_split <- ifelse(mtcars$disp <= median(mtcars$disp), "below_median","above_median")
mtcars$quantile_split <- cut(mtcars$disp, breaks = c(0, quantile(mtcars$disp)),labels = c("1_quartile",paste0(1:4, "_quartile")))
This works nicely for the whole dataset, but how can I do this for each cyl separately, please?
So, I am hoping to print the median/quartile split labels based on disp values within each cyl group. Thank you.
This can be accomplished using the dplyr package:
library(dplyr)
mtcars %>%
select(cyl, disp) %>%
group_by(cyl) %>%
mutate(median_split = ifelse(disp <=median(disp), "below_median","above_median"),
quartile_split = cut(disp, breaks = c(0, quantile(disp)), labels = c("1_quartile",paste0(1:4, "_quartile")))) %>%
arrange(cyl)
This code groups the data by the cyl column and then computes the median_split and quartile_split based on the disp values within each cyl group.

Combine groups into one group to display in boxplot (ggplot2, R)

I am using the mtcars dataset as an example and I use this code.
library(ggplot2)
library(ggsci)
ggviolin(mtcars, x="cyl", y="disp", fill="cyl", palette="jco", facet.by = "am")
To each facet, I would like to add a fourth category on the x-axis (maybe call this "6or8"), in which the 6- and 8-cylinder groups (but not the 4-cylinder group) are combined. I found this similar post, but it did not help me, because of my facets and addition of two instead of all categories.
Does anyone have a suggestion? Thank you.
You could try this:
> newmtcars <- rbind(mtcars %>% mutate(cyl = as.character(cyl)),
+ mtcars %>% filter(cyl %in% c(6,8)) %>% mutate(cyl = '6or8')) %>% arrange(cyl)
> ggviolin(newmtcars, x="cyl", y="disp", fill="cyl", palette="jco", facet.by = "am")
You can manually change the levels for cyl to change the ordering in the plot (if, for example, you want "6or8" to be the first/last level).

Creating a scatter plot using two data sets in R

Beginner here. I'm hoping to create a scatterplot using two datasets that I created using group by:
menthlth_perc_bystate <- brfss2013 %>%
group_by(state) %>%
summarise(percent_instability = sum(menthlth > 15, na.rm = TRUE) / n()) %>%
arrange(desc(percent_instability))
exercise_perc_bystate <- brfss2013 %>%
group_by(state) %>%
summarise(perc_exercise = sum(exeroft1 > 30, na.rm = TRUE) / n()) %>%
arrange(desc(perc_exercise))
I want to merge these into one dataset, total_data. Both have 54 obs.
total_data <- merge(menthlth_perc_bystate,exercise_perc_bystate,by="state")
Presumably the scatter plot would take on one axis the state's percent instability (menthlth_perc_bystate) and on another the states percent exercise (exercise_perc_by_state). I tried this using ggplot but got an error:
ggplot(total_data, aes(x = total_data$menthlth_perc_bystate, y = total_data$exercise_perc_bystate)) + geom_point()
The error: Aesthetics must be either length 1 or the same as the data (54): x, y
In the aes() function of ggplot you put the bare column names from the data frame you provided for the data argument. So in your example it would be:
ggplot(total_data ,
aes(x = percent_instability,
y = perc_exercise)) +
geom_point()
Although I'm not sure what total_ex is in your example.
Also, using total_ex$menthlth_perc_bystate implies you are looking for a column named menthlth_perc_bystate in the data frame total_ex. That column does not exist, it is the name of a different data frame. Once you have merged the two data frames, the columns in the resulting data frame will be state, percent_instability, and perc_exercise.

Is there a way to `pipe through a list'?

One really cool feature from the ggplot2 package that I never really exploited enough was adding lists of layers to a plot. The fun thing about this was that I could pass a list of layers as an argument to a function and have them added to the plot. I could then get the desired appearance of the plot without necessarily returning the plot from the function (whether or not this is a good idea is another matter, but it was possible).
library(ggplot2)
x <- ggplot(mtcars,
aes(x = qsec,
y = mpg))
layers <- list(geom_point(),
geom_line(),
xlab("Quarter Mile Time"),
ylab("Fuel Efficiency"))
x + layers
Is there a way to do this with pipes? Something akin to:
#* Obviously isn't going to work
library(dplyr)
action <- list(group_by(am, gear),
summarise(mean = mean(mpg),
sd = sd(mpg)))
mtcars %>% action
To construct a sequence of magrittr steps, start with .
action = . %>% group_by(am, gear) %>% summarise(mean = mean(mpg), sd = sd(mpg))
Then it can be used as imagined in the OP:
mtcars %>% action
Like a list, we can subset to see each step:
action[[1]]
# function (.)
# group_by(., am, gear)
To review all steps, use functions(action) or just type the name:
action
# Functional sequence with the following components:
#
# 1. group_by(., am, gear)
# 2. summarise(., mean = mean(mpg), sd = sd(mpg))
#
# Use 'functions' to extract the individual functions.

Resources