0

I have three variables in my data frame. A, B and C. I am interested in the relative frequency of C given combinations of A & B.

My dataset using dput:

structure(list(B = structure(c(1L, 1L, 3L, 3L, 3L, 2L), .Label = c("text1", 
"text2", "text3"), class = "factor"), A = structure(c(3L, 
4L, 4L, 2L, 2L, 3L), .Label = c("Control_base", "Control_info", 
"TreatA", "TreatB"), class = "factor"), , C = structure(c(1, 
0, 2, 3, 2, 3), format.stata = "%9.0g", labels = c(somea = 0, 
someb = 1, somec = 2, somed = 3), class = c("haven_labelled", "vctrs_vctr", 
"double"))), row.names = c(NA, -6L), class = c("tbl_df", "tbl", 
"data.frame"))
 

I want to use sjplot plot_grpfrq however, I would want 4 plots (for my four categories of B). However this code does not work:

data %>% group_by(B) %>% 
 plot_grpfrq(
    var.cnt = data$A, 
    var.grp = data$C) %>%
  plot_grid()

Giving the error: Error in match.arg(type) : 'arg' must be NULL or a character vector

This code works:

plot_grpfrq(
    var.cnt = data$A, 
    var.grp = data$C) 

These codes also work:

data %>% group_by(B) %>% 
  plot_frq(C) %>%
  plot_grid()

and

data %>% group_by(A) %>% 
  plot_frq(C) %>%
  plot_grid()

Is there anything I am missing here?

canIchangethis
  • 87
  • 1
  • 10

1 Answers1

2

You could use group_map to generate a list with a plot for each group, so that it can be processed by plot_grid:

library(dplyr)
data %>% group_by(B) %>%
         group_map(~plot_grpfrq(var.cnt = .x$A,
                                var.grp = .x$C)) %>%
         plot_grid()

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78
  • Thank you, that is very helpful. I am just curious, do you also get the Warning: In plot_grid(.) : Not enough tags labels in list. Using letters instead. Because actually instead of As and A/B/C there should be my labels and they don't show. (however if I change B with .x$A for example, I do indeed see the labels, however the three (or 4) subplots are always just getting A/B/C/(D) – canIchangethis Nov 14 '22 at 08:10
  • I should say, replacing plot_grid() with plot_grid(, label = c("label1", "label2", "label3")) does not work because of unused argument – canIchangethis Nov 14 '22 at 08:30
  • Sadly, it also just don't work for me @Waldi because it always gives me all data so each plot looks 100% the same content wise =( – canIchangethis Nov 14 '22 at 08:36