简体   繁体   中英

How to use sjplot in R function plot_grpfrq in a "facet grid" way based on another variable

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?

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM