Additional File 2.txt: File containing R code used to perform the analysis.

## R code starts here:
library(ggplot2)
library(tximport)
library(stats)
library(reshape)
library(qsmooth)
library(edgeR)
library(EnhancedVolcano)
library(fgsea)
library(msigdb)
library(msigdbi)
library(ggpubr)
library(ggrepel)
library(enrichplot)

#before running, make sure to update paths to files
path <- <path_to_output_directory>

samples <- c("PM-B1", "PM-B2", "PM-B3", "PM-E1") 

TxDb <- <read_file_with_gene2transcripts_gencode_v35>

colnames(TxDb) <- c("GENE_ID","TX_ID","GENE_BIOTYPE","GENE_NAME")

Tx = TxDb[,c("TX_ID","GENE_ID")]

#read in Kallisto expression
files <- file.path(path, paste0(samples,"/", "abundance.tsv"))
names(files) <- samples

txi.kallisto <- tximport(  files, type = "kallisto", txOut = FALSE , tx2gene=Tx ,
                           ignoreAfterBar=TRUE , ignoreTxVersion=FALSE) 

#extract counts
cts <- txi.kallisto$counts

#group gene biotypes:
pseudogene <- c("unprocessed_pseudogene", "processed_pseudogene", "transcribed_unprocessed_pseudogene",
                "rRNA_pseudogene", "polymorphic_pseudogene", "translated_processed_pseudogene",
                "IG_V_pseudogene", "transcribed_processed_pseudogene", "transcribed_unitary_pseudogene",
                "unitary_pseudogene", "translated_unprocessed_pseudogene", "pseudogene",
                "TR_V_pseudogene", "IG_C_pseudogene")


ncRNA <- c("miRNA", "miscRNA", "piRNA", "rRNA", "siRNA", "snRNA", "snoRNA", "tRNA", "vaultRNA",
           "misc_RNA", "scRNA", "scaRNA", "Mt_rRNA", "ribozyme")

IG_gene <- c("IG_C_gene", "IG_D_gene", "IG_J_gene", "IG_V_gene")

TR_gene <- c("TR_C_gene", "TR_D_gene", "TR_J_gene", "TR_V_gene")

TR_IG_TEC <- c(IG_gene, TR_gene, "TEC")

#select genes expressed across all 4 samples
expressed <- rownames(cts)[rowSums(apply(cts,2, function(x) x>0))==4]

#extract gene information about expressed genes
expressed_info <- unique(TxDb[TxDb$GENE_ID %in% expressed,c("GENE_ID","GENE_NAME", "GENE_BIOTYPE")])

biotypes <- data.frame(table(expressed_info$GENE_BIOTYPE))
biotypes$Var1 <- as.character(biotypes$Var1)
biotypes[biotypes$Var1 %in% ncRNA,"Var1"] <- "ncRNA"
biotypes[biotypes$Var1 %in% pseudogene,"Var1"] <- "pseudogene"
biotypes[biotypes$Var1 %in% TR_IG_TEC,"Var1"] <- "TR_IG_TEC"

biotypes <- aggregate(biotypes$Freq, by=list(Var1=biotypes$Var1), FUN=sum)
dataplot <- data.frame(group=biotypes$Var1, value=biotypes$x)

p <- ggplot(data = dataplot, aes(x = "", y = value, fill = group)) + 
  geom_bar(stat="identity", width=1, size = 1, color = "white") +
  geom_label_repel(aes(label = value), max.overlaps=Inf) +
  coord_polar(theta = "y") + theme_classic()
 
#extract Kallisto TPM expression and check expression of S and E marker genes
tpms <- txi.kallisto$abundance[expressed,]

tpms_global <- data.frame(tpms)
tpms_global$GENE_NAME <- expressed_info$GENE_NAME

globalMean <- mean(colMeans(tpms))

#read in genes From Blum et al. 2019
se_signature <- <path_to_additional_file_1>

s_markers <- se_signature[se_signature$Component == "S-comp",]
e_markers <- se_signature[se_signature$Component == "E-comp",]

s_markersG <- unlist(strsplit(s_markers$Gene.Names, "/// "))
e_markersG <- unlist(strsplit(e_markers$Gene.Names, "/// "))

s_geneID <- unique(TxDb[TxDb$GENE_NAME %in% s_markersG,c("GENE_ID", "GENE_NAME")])
e_geneID <- unique(TxDb[TxDb$GENE_NAME %in% e_markersG,c("GENE_ID", "GENE_NAME")])

#overlap with S and E genes in PM-EVs:
sum(rownames(tpms) %in% s_geneID$GENE_ID) 
sum(rownames(tpms) %in% e_geneID$GENE_ID) 

#distribution of expression of S and E markers across PM-EVs:
df_s <- reshape::melt(tpms[rownames(tpms) %in% s_geneID$GENE_ID,])
df_e <- reshape::melt(tpms[rownames(tpms) %in% e_geneID$GENE_ID,])
df_s$component <- "S"
df_e$component <- "E"
df_se <- rbind(df_s, df_e)

p <- ggplot(df_se, aes(x = X2, y=log2(value+1), fill=component)) +  geom_hline(yintercept = log2(globalMean+1), linetype="dotted") +
  geom_boxplot() + theme_classic() + ylim(0, 15) + labs(y = "log2(TPM+1)") + stat_compare_means()

#load Plasma-EV data:
samplesPlasma <- <file_with_plasma_ev_sample_names>
filesPlasma <- file.path(paste0(path, samplesPlasma$V1,"/", "abundance.tsv"))
names(filesPlasma) <- samplesPlasma$V1

Plasmatxi.kallisto <- tximport(  filesPlasma, type = "kallisto", txOut = FALSE , tx2gene=Tx ,
                           ignoreAfterBar=TRUE , ignoreTxVersion=FALSE)

#extract Kallisto counts
Plasmacts <- Plasmatxi.kallisto$counts

all <- cbind(Plasmacts, cts)
gFactor <- c(rep("Plasma",ncol(Plasmacts)), rep("PM",ncol(cts)) )

#use qsmooth normalization to remove batch effects
smoothed <- qsmooth(object = all, group_factor = factor(gFactor))

#run differential gene expression with edgeR
grouping <- factor(gFactor, levels = c("Plasma","PM"))
cds <- DGEList(counts = qsmoothData(smoothed), group = grouping)
cds <- cds[expressed,]

#filter out lowly expressed genes
keep <- filterByExpr(cds, min.count = 20)
cds <- cds[keep, keep.lib.sizes=FALSE]
cds <- calcNormFactors(cds, method = "TMM")

design <- model.matrix(~ 0 + grouping)
rownames(design) <- colnames(cds)
colnames(design) <- levels(grouping)
cds <- estimateDisp(cds, design, robust=TRUE)

fit <- glmQLFit(cds, design, robust=TRUE)
con <- makeContrasts(PM - Plasma, levels=design )
qlf <- glmQLFTest(fit, contrast=con)

res <- glmQLFTest(fit, contrast=con)
res_all <- topTags(res, n=dim(res$table)[1])

#assign gene names to gene IDs
res_all_tmp <- unique(TxDb[TxDb$GENE_ID %in% rownames(res_all$table),c("GENE_ID", "GENE_NAME")])
for (i in 1:nrow(res_all$table)){
	res_all$table$GENE_NAME[i] <- res_all_tmp[res_all_tmp$GENE_ID == rownames(res_all$table)[i],"GENE_NAME"]
}

p <- EnhancedVolcano(res_all$table,
    lab = "",
    x = 'logFC',
    y = 'FDR',
    title = 'PM-EV vs. Plasma-EV',
    pCutoff = 0.05,
    FCcutoff = 1,
    pointSize = 3.0,
    labSize = 6.0,
    caption = bquote(~Log[2]~ "Log2 fold change cutoff 1; q-value cutoff 0.05"),
    ylab = bquote('-' ~Log[10]~ 'q-value'),
    xlab = bquote(~Log[2]~ 'fold change'))
   
#S and E genes:
res_all$table$marker <- ""
res_all$table[res_all$table$GENE_NAME %in% s_markersG,"marker"] <- "S"
res_all$table[res_all$table$GENE_NAME %in% e_markersG,"marker"] <- "E"

#plot biotypes of up- and down-regulated genes in PM-EVs:
all_up <- res_all$table[res_all$table$logFC > 1 & res_all$table$FDR < 0.05,]
all_down <- res_all$table[res_all$table$logFC < -1 & res_all$table$FDR < 0.05,]

g_up <- unique(TxDb[TxDb$GENE_ID %in% rownames(all_up),c("GENE_ID", "GENE_BIOTYPE")])
g_down <- unique(TxDb[TxDb$GENE_ID %in% rownames(all_down),c("GENE_ID", "GENE_BIOTYPE")])

biotypes_all_up <- data.frame(table(g_up$GENE_BIOTYPE))
biotypes_all_down <- data.frame(table(g_down$GENE_BIOTYPE))

#pseudogenes of genes up:
pseudogene_sum <- sum(biotypes_all_up[biotypes_all_up$Var1 %in% pseudogene,"Freq"])
ncRNA_sum <- sum(biotypes_all_up[biotypes_all_up$Var1 %in% ncRNA,"Freq"])
TR_IG_TEC_sum <- sum(biotypes_all_up[biotypes_all_up$Var1 %in% TR_IG_TEC,"Freq"])

biotypes_all_up_df <-  biotypes_all_up[biotypes_all_up$Var1 %in% c("lncRNA", "protein_coding"),]
biotypes_all_up_df <- rbind(biotypes_all_up_df, data.frame(Var1=c("pseudogene", "ncRNA", "other"), 
Freq = c(pseudogene_sum, ncRNA_sum, TR_IG_TEC_sum)))

#pseudogenes of genes down:
pseudogene_sum_down <- sum(biotypes_all_down[biotypes_all_down$Var1 %in% pseudogene,"Freq"])
ncRNA_sum_down <- sum(biotypes_all_down[biotypes_all_down$Var1 %in% ncRNA,"Freq"])
TR_IG_TEC_sum_down <- sum(biotypes_all_down[biotypes_all_down$Var1 %in% TR_IG_TEC,"Freq"])

biotypes_all_down_df <-  biotypes_all_down[biotypes_all_down$Var1 %in% c("lncRNA", "protein_coding"),]
biotypes_all_down_df <- rbind(biotypes_all_down_df, data.frame(Var1=c("pseudogene", "ncRNA", "other"), 
Freq = c(pseudogene_sum_down, ncRNA_sum_down, TR_IG_TEC_sum_down)))

biotypes_all_down_df$group <- "PM-EV depleted"
biotypes_all_up_df$group <- "PM-EV enriched"

biotypes_df <- rbind(biotypes_all_down_df, biotypes_all_up_df)
biotypes_df <- data.frame(PM_EV_enriched = biotypes_all_up_df$Freq, PM_EV_depleted = biotypes_all_down_df$Freq)
rownames(biotypes_df) <- biotypes_all_down_df$Var1

bar <- barplot(as.matrix(biotypes_df), 
        border="white", 
        font.axis=2, 
        beside=T, 
        legend=rownames(biotypes_df), 
        xlab="group", 
        ylab = "Number of genes",
        font.lab=2)

#Get transcript lengths of the depleted and enriched lncRNA and protein-coding genes
transcriptInfo <- <read_additional_file_1>
colnames(transcriptInfo) <- c("start", "end", "length")

transcriptInfo$TX <- rownames(transcriptInfo)
lncs_up_tx <- TxDb[TxDb$GENE_ID %in% g_up[g_up$GENE_BIOTYPE=="lncRNA","GENE_ID"],c("TX_ID", "GENE_ID")]

joined_df_up <- merge(lncs_up_tx, transcriptInfo, by.x = "TX_ID", 
             by.y = "TX", all.x = TRUE, all.y = FALSE)

#pick the longest transcript for each gene:
longest_up <- c()
for (g in unique(joined_df_up$GENE_ID)){
	tmp <- joined_df_up[joined_df_up$GENE_ID == g,]
	longest_up <- c(longest_up, max(tmp$length))
}         
             
lncs_down_tx <- TxDb[TxDb$GENE_ID %in% g_down[g_down$GENE_BIOTYPE=="lncRNA","GENE_ID"],c("TX_ID","GENE_ID")]
joined_df_down <- merge(lncs_down_tx, transcriptInfo, by.x = "TX_ID", 
             by.y = "TX", all.x = TRUE, all.y = FALSE)
 
longest_down <- c()
for (g in unique(joined_df_down$GENE_ID)){
	tmp <- joined_df_down[joined_df_down$GENE_ID == g,]
	longest_down <- c(longest_down, max(tmp$length))
}         

#violin plot for transcript length of lncRNA
df_tx <- data.frame(length = c(longest_up, longest_down),
group = c(rep("enriched", length(longest_up)), rep("depleted", length(longest_down))))
df_tx$group <- factor(df_tx$group, levels = c("enriched", "depleted"))

p <- ggplot(df_tx, aes(x=group, y=length/1000, fill=group)) + 
  geom_violin() + 
  geom_boxplot(width=0.1) +stat_compare_means(size=6) + theme_minimal() + 
  ggtitle("Transcript length of lncRNA") + labs(x = "", y = "transcript length [kb]")
 
mean(df_tx[df_tx$group=="enriched","length"])/1000
mean(df_tx[df_tx$group=="depleted","length"])/1000

#repeat for the protein-coding genes
protein_up_tx <- TxDb[TxDb$GENE_ID %in% g_up[g_up$GENE_BIOTYPE=="protein_coding","GENE_ID"],c("TX_ID", "GENE_ID")]

joined_df_up_prot <- merge(protein_up_tx, transcriptInfo, by.x = "TX_ID", 
             by.y = "TX", all.x = TRUE, all.y = FALSE)
            
longest_up_protein <- c()
for (g in unique(joined_df_up_prot$GENE_ID)){
	tmp <- joined_df_up_prot[joined_df_up_prot$GENE_ID == g,]
	longest_up_protein <- c(longest_up_protein, max(tmp$length))
}         
             
protein_down_tx <- TxDb[TxDb$GENE_ID %in% g_down[g_down$GENE_BIOTYPE=="protein_coding","GENE_ID"],c("TX_ID","GENE_ID")]
joined_df_down_prot <- merge(protein_down_tx, transcriptInfo, by.x = "TX_ID", 
             by.y = "TX", all.x = TRUE, all.y = FALSE)
 
longest_down_protein <- c()
for (g in unique(joined_df_down_prot$GENE_ID)){
	tmp <- joined_df_down_prot[joined_df_down_prot$GENE_ID == g,]
	longest_down_protein <- c(longest_down_protein, max(tmp$length))
}         

#violin plot for transcript length of protein-coding genes
df_tx_prot <- data.frame(length = c(longest_up_protein, longest_down_protein),
group = c(rep("enriched", length(longest_up_protein)), rep("depleted", length(longest_down_protein))))
df_tx_prot$group <- factor(df_tx_prot$group, levels = c("enriched", "depleted"))

p <- ggplot(df_tx_prot, aes(x=group, y=length/1000, fill=group)) + 
  geom_violin() + geom_boxplot(width=0.1) + stat_compare_means(size=6) + 
  theme_minimal() + ggtitle("Transcript length of protein coding") +
  labs(x = "", y = "transcript length [kb]")

mean(df_tx_prot[df_tx_prot$group=="enriched","length"])/1000
mean(df_tx_prot[df_tx_prot$group=="depleted","length"])/1000

#load file with number of exons:
exons <- <read_additional_file_1>
colnames(exons) <- c("no_exons", "TX_ID")

joined_df_up <- merge(joined_df_up, exons, by.x = "TX_ID", 
                      by.y = "TX_ID", all.x = TRUE, all.y = FALSE)
longest_up_exon <- c()
for (g in unique(joined_df_up$GENE_ID)){
  tmp <- joined_df_up[joined_df_up$GENE_ID == g,]
  count <- tmp[tmp$length == max(tmp$length),"no_exons"]*1000 / max(tmp$length)
  longest_up_exon <- c(longest_up_exon, count)
}         

joined_df_down <- merge(joined_df_down, exons, by.x = "TX_ID", 
                      by.y = "TX_ID", all.x = TRUE, all.y = FALSE)
longest_down_exon <- c()
for (g in unique(joined_df_down$GENE_ID)){
  tmp <- joined_df_down[joined_df_down$GENE_ID == g,]
  count <- tmp[tmp$length == max(tmp$length),"no_exons"]*1000 / max(tmp$length)
  longest_down_exon <- c(longest_down_exon, count)
}         


#violin plot for number of exons per 1kb in lncRNA
df_tx_exons <- data.frame(count = c(longest_up_exon, longest_down_exon),
                    group = c(rep("enriched", length(longest_up_exon)), rep("depleted", length(longest_down_exon))))
df_tx_exons$group <- factor(df_tx_exons$group, levels = c("enriched", "depleted"))

p <- ggplot(df_tx_exons, aes(x=group, y=count, fill=group)) + 
  geom_violin() + geom_boxplot(width=0.1) +stat_compare_means(size=6) + theme_minimal() + 
  ggtitle("lncRNA") + labs(x = "", y = "count of exons per 1kb")

mean(df_tx_exons[df_tx_exons$group=="depleted","count"])
mean(df_tx_exons[df_tx_exons$group=="enriched","count"])

#and for protein-coding genes:
joined_df_up_prot <- merge(joined_df_up_prot, exons, by.x = "TX_ID", 
                           by.y = "TX_ID", all.x = TRUE, all.y = FALSE)
longest_up_protein_exon <- c()
for (g in unique(joined_df_up_prot$GENE_ID)){
  tmp <- joined_df_up_prot[joined_df_up_prot$GENE_ID == g,]
  count <- tmp[tmp$length == max(tmp$length),"no_exons"]*1000 / max(tmp$length)
  longest_up_protein_exon <- c(longest_up_protein_exon, count)
}         

joined_df_down_prot <- merge(joined_df_down_prot, exons, by.x = "TX_ID", 
                           by.y = "TX_ID", all.x = TRUE, all.y = FALSE)
longest_down_protein_exon <- c()
for (g in unique(joined_df_down_prot$GENE_ID)){
  tmp <- joined_df_down_prot[joined_df_down_prot$GENE_ID == g,]
  count <- tmp[tmp$length == max(tmp$length),"no_exons"]*1000 / max(tmp$length)
  longest_down_protein_exon <- c(longest_down_protein_exon, count)
}         

#violin plot for transcript length of lncRNA
df_tx_prot_exon <- data.frame(count = c(longest_up_protein_exon, longest_down_protein_exon),
                         group = c(rep("enriched", length(longest_up_protein_exon)),
                                   rep("depleted", length(longest_down_protein_exon))))

df_tx_prot_exon$group <- factor(df_tx_prot_exon$group, levels = c("enriched", "depleted"))
p <- ggplot(df_tx_prot_exon, aes(x=group, y=count, fill=group)) + 
  geom_violin() + geom_boxplot(width=0.1) + stat_compare_means(size=6) + theme_minimal() + 
  ggtitle("protein coding RNA") + labs(x = "", y = "count of exons per 1kb")

mean(df_tx_prot_exon[df_tx_prot_exon$group=="enriched","count"])
mean(df_tx_prot_exon[df_tx_prot_exon$group=="depleted","count"])

#run gene set enrichment analysis: 

hallmark = <path_to_msigdb_hallmarks_file>
hallmark_set <- read.gmt(hallmark)

all_up <- all_up[order(all_up$logFC, decreasing=TRUE),]
all_down <- all_down[order(all_down$logFC),]

ups <- rep(1, nrow(all_up))
names(ups) <- all_up$GENE_NAME

downs <- rep(1, nrow(all_down))
names(downs) <- all_down$GENE_NAME

#order genes based on logFoldChange
geneOrder <- rep(1, nrow(res_all$table))
res_all$table <- res_all$table[order(res_all$table$logFC, decreasing=TRUE),]
names(geneOrder) <- res_all$table$GENE_NAME

set.seed(123)
fgsea_all <- fgsea(pathways = hallmark_set$genesets, stats = geneOrder, minSize= 15, maxSize = 500, eps = 0, scoreType = "std", nproc = 10)
collapsed <- collapsePathways(fgsea_all[order(pval)][padj < 0.01], hallmark_set$genesets, geneOrder)
mainPathways <- fgsea_all[pathway %in% collapsed$mainPathways][order(-NES), pathway]

toPlot <- fgsea_all[fgsea_all$pathway %in% mainPathways,]
toPlot$pathway <- gsub("HALLMARK_", "", toPlot$pathway)
toPlot$pathway <- gsub("_", " ", toPlot$pathway)

tp <- ggplot(toPlot, aes(reorder(pathway, NES), NES)) +
  geom_col(aes(fill=padj)) +
  labs(x="Pathway", y="Normalized Enrichment Score",
       title="Hallmark pathways NES from GSEA") + theme_minimal() +
  theme(axis.text.x = element_text(angle=90))

#look at the top 3 enriched pathways
fgsea_sel <- fgsea_all[  fgsea_all$pathway %in% c("HALLMARK_EPITHELIAL_MESENCHYMAL_TRANSITION", "HALLMARK_GLYCOLYSIS", "HALLMARK_HYPOXIA"),c("pathway","leadingEdge")]
x <- list(EMT = fgsea_sel[1,"leadingEdge"][[1]][[1]], Glycolysis = fgsea_sel[2,"leadingEdge"][[1]][[1]],
          Hypoxia = fgsea_sel[3,"leadingEdge"][[1]][[1]])
logFC <- res_all$table[res_all$table$GENE_NAME %in% unique(unlist(x)),"logFC"]
names(logFC) <- res_all$table[res_all$table$GENE_NAME %in% unique(unlist(x)),"GENE_NAME"]

#check for S and E markers genes and transcriptional factors
tfs <- <read_file_with_transcriptional_factors_from_FANTOM5>
x_all <- list(EMT = fgsea_sel[1,"leadingEdge"][[1]][[1]], Glycolysis = fgsea_sel[2,"leadingEdge"][[1]][[1]],
              Hypoxia = fgsea_sel[3,"leadingEdge"][[1]][[1]])

#genes that are enriched in PM-EVs
x_all$EMT <- x_all$EMT[x_all$EMT %in% x_all$EMT[logFC[x_all$EMT]>0]] 
x_all$Glycolysis <- x_all$Glycolysis[x_all$Glycolysis %in% x_all$Glycolysis[logFC[x_all$Glycolysis]>0]]
x_all$Hypoxia <- x_all$Hypoxia[x_all$Hypoxia %in% x_all$Hypoxia[logFC[x_all$Hypoxia]>0]]

#genes that are S and E marker genes or transciptional factors
x_small <- list()
x_small$EMT <- x_all$EMT[x_all$EMT %in% c(s_markersG, e_markersG, tfs$V1)]
x_small$Hypoxia <- x_all$Hypoxia[x_all$Hypoxia %in% c(s_markersG, e_markersG, tfs$V1)]
x_small$Glycolysis <- x_all$Glycolysis[x_all$Glycolysis %in% c(s_markersG, e_markersG, tfs$V1)]

p <- cnetplot(x_small, foldChange=logFC, cex_gene=2, cex_label_gene=1.1, layout="kk") 

#plot qPCR analysis results
q_res <- read.csv(paste0(path, "qPCR_results.txt"), header=TRUE, sep='\t')

for (gene in unique(q_res$Gene)){
  tmp <- q_res[q_res$Gene==gene,]
  r <- ggplot(tmp, aes(x = RE.Delta.Ct, y = RC.Delta.Ct)) + geom_point(size=5) + theme_bw() + 
    ggtitle(gene) + labs(x = "EVs [Delta Ct]", y = "Cells [Delta Ct]") +
    stat_cor(method = "pearson", size=6) + 
    geom_point(data =tmp, aes(x = RE.Delta.Ct, y = RC.Delta.Ct, color=Sample), size=5)
  plot(r)
  
}


#run survival analysis using TCGA-MESO dataset:
meso_tcga <- read.table(paste0(path, "TCGA_MESO_rsem.txt"), header=TRUE, sep='\t', row.names=1)

#the data is log(x+1), reverse:
meso_tcga <- 2^meso_tcga - 1 

clinical <- read.table(paste0(path, "TCGA_MESO_clinical.txt"),header=TRUE, sep='\t')
clinical$sample <- gsub("-", ".", clinical$bcr_patient_barcode)

#select common samples:
colnames(meso_tcga) <- substr(colnames(meso_tcga), 1, 12)
comS <- Reduce(intersect, list(colnames(meso_tcga), clinical$sample))

rownames(clinical) <- clinical$sample
clinical <- clinical[comS,]

genes <- c("MMP2", "GREM1", "COL6A3", "COL1A2", "PRRX1", "SNAI2", "GEM", "MSX1", "JUN",
           "SRPX", "MAFF", "DDIT3", "KLF6", "CAV1", "ATF3", "FOSL2", "ENO1", "ANKZF1", "SOX9", "ABCB6",
           "ANXA8", "UCHL1", "C3", "GAS5", "LAMC2", "SNHG9", "SNHG11")

clinical <- cbind(clinical, t(meso_tcga[genes,comS]))

cox_results <- data.frame( hazard=numeric(), lower=numeric(),  upper=numeric(), p= numeric()) #to store results from univariate test
cox_results_multi <- data.frame( hazard=numeric(), lower=numeric(),  upper=numeric(), p= numeric()) #to store results from multivariate test

for (i in 10:(ncol(clinical)) ){
    clinical[,i] <- scale(clinical[,i])
    loop = "Surv(OS.time, OS) ~ "
    loop <- paste0(loop,colnames(clinical)[i])
    res.cox <- coxph(as.formula(loop), data =  clinical)
    
    cox_results[colnames(clinical)[i],"p"] <- as.vector( summary(res.cox)$coefficients[,"Pr(>|z|)"] )
    cox_results[colnames(clinical)[i],"hazard"] <- exp(res.cox$coef)
    cox_results[colnames(clinical)[i],"lower"] <- summary(res.cox)$conf.int[3]
    cox_results[colnames(clinical)[i],"upper"] <- summary(res.cox)$conf.int[4]

    loop2 = "Surv(OS.time, OS) ~ age_at_initial_pathologic_diagnosis + ajcc_pathologic_tumor_stage +"
    
    loop2 <- paste0(loop2,colnames(clinical)[i])
    
    res.cox2 <- coxph(as.formula(loop2), data =  clinical)
    
    cox_results_multi[colnames(clinical)[i],"p"] <- as.vector( summary(res.cox2)$coefficients[colnames(clinical)[i],"Pr(>|z|)"] )
    cox_results_multi[colnames(clinical)[i],"hazard"] <- exp(res.cox2$coef[colnames(clinical)[i]])
    cox_results_multi[colnames(clinical)[i],"lower"] <- summary(res.cox2)$conf.int[colnames(clinical)[i],3]
    cox_results_multi[colnames(clinical)[i],"upper"] <- summary(res.cox2)$conf.int[colnames(clinical)[i],4]
}


cox_results$gene <- factor(rownames(cox_results), levels = rownames(cox_results))

breaks <- rownames(cox_results)

#plot results
coxplot <- ggplot(cox_results, aes(y=gene))+
  geom_linerange(aes(xmin=lower,xmax=upper),linetype=1,color="black")+
  geom_point(aes(x=lower),size=1,color="black")+
  geom_point(aes(x=upper),size=1,color="black")+
  geom_point(aes(x=hazard),size=3,color="black")+
  theme_bw() + scale_y_discrete(breaks = breaks) +
  annotate("text", x = 3, y = cox_results$gene, label = finalfit::p_tidy(cox_results$p, digits = 3, prefix = NULL),  size=6) + 
  theme(plot.margin = unit(c(1, 10, 1, 1), "lines")) +
  coord_cartesian( xlim = c(0.2,2.5),clip = "off") + theme(axis.text = element_text(size=12, color="black")) +
  geom_vline(xintercept = 1, linetype=2, color="gray") + labs(x="Hazard ratio")                              






