Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206235

How to reorder factors based on degree of absolute differences of dodged variables

$
0
0

I have a dataframe of binary categorical variable V0 (A, B), and 22 (V1-V22) continuous variables representing different cell types. My end goal is to have boxplot with dodged boxes based on V0, arranged based on "absolute difference of mean" between A and B within each of the V1-V22 types.

Thank you

library(reshape2)
library(ggplot2)
library(forcats)
library(ggpubr)

## dummy data frame

a <- as.data.frame(sample(c('A', 'B'), 10000, replace=TRUE))
b <- data.frame(replicate(5,sample(rnorm(n = 10000, mean = c(0, 5, 20), sd = c(1, 5, 20)))))
c <- data.frame(replicate(5,sample(rnorm(n = 10000, mean = c(3, 6, 9), sd = c(1, 4, 5)))))
x <- cbind(a,b,c)
colnames(x) <- c("v0", "v1", "2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10")

## ## melt data frame
x_melt <- melt(x, id.vars = c("v0"))

## plot
ggplot(x_melt, aes(x= fct_reorder(variable, value, .fun =mean, .desc = T),
                   y=(value)))+
  geom_boxplot(aes(fill=v0), outlier.alpha = 0, coef = 0, alpha = 0.9)+
  labs(x="variable", y="value", fill="Race")+
  stat_compare_means(aes(group = v0), 
                     label = "p.signif", label.y.npc = 0.5, hide.ns=T)

So basically, I want the absolute difference between A and B to be the value upon which variables V1:v10 are ordered:

plot


Viewing all articles
Browse latest Browse all 206235

Trending Articles