how to calculate median and length for different groups?

Viewed 36

I combined the file containing 4 different samples. The reads for each sample come from A or B sequencing. I want to create a plot of read length for each tissue by A-B .my input is alltissues.tsv

Brain   A   1311
..
Brain   B   1337
..
Heart   A   1411
Heart   B   1308
Tissue3 A 5300
Tissue3 B  1444
Tissue4 A 5555
Tissue4 B  1233

When I run this script It is calculating all reads according to A and B for all tissues. How can I caclculate the readlength for each tissue by A and B? I got really stuck here. If you help me i would appreciate.

library(ggplot2)
library(scales)

plot <- read.table("~/Documents/readlength_all.tsv", header=F, as.is=T,   sep="\t")

colnames(plot)<-c("tissue", "type", "count")
plot$type=factor(plot$type, levels=c("A", "B"))
plot$tissue=factor(plot$tissue, levels=c( "Brain", "Heart", "Tissue3", "Tissue4",))
list=c("A","B")
label=matrix(0,2*length(list),2)
z=1
for (i in 1:length(list))

median=median(plot[plot$type==list[i], 3],na.rm=T)
len=length(plot[plot$type==list[i], 3])
t=paste("N =", prettyNum(len,big.mark=",",scientific=FALSE), "\nMedian =",  prettyNum(round(median,2),big.mark=",",scientific=FALSE))
label[i,1]=list[i]
label[i,2]=t
z=z+1
1 Answers

You could use the tidyverse set of packages.

library(tidyverse)

data <- tibble(
  tissue = rep(c("brain", "leg", "arm"), each = 10),
  type = rep(c("A", "B"), times = 15),
  value = rnorm(30, 1000, 150)
)

data_summary <- data %>% 
  group_by(tissue, type) %>% 
  summarise(
    number_of_observations = n(),
    median = quantile(value, 0.5)
  )

data_summary %>% 
  ggplot(aes(x = tissue,
             y = median,
             fill = type)) +
  geom_bar(stat = "identity",
           position = position_dodge() ) + 
  theme_bw()

You can learn more about grouping and summarising here: https://rstudio.cloud/learn/primers/2

Related