'Missing list entry in loop causes ggplot2 and patchwork failure

I am trying to write a script that will generate violin plots with seurat for single cell sequencing data. I am looking for cell type clusters. Seurat makes a ggplot object and I can combine them with Patchwork. I have to make many violin plots, but it would work for all of the plots seurat makes, typically there are 15-20 Ensembl IDs and I don't know ahead of time if the ID is present in the data and it isn't the script dies. I am using R tryCatch from an earlier SO answer here 1,

Here is my code example:

library(dplyr)
library(Seurat)
library(BiocParallel)
library(ggplot2)
library(patchwork)
library(data.table)

setDTthreads(0)

# loads the seurat object with the data 'lonza.sub'
load("12May22_2.RData")

today <- Sys.Date()
dt <- format(today, format="%d%b%y")

## Data from https://www.abcam.com/neuroscience/neural-markers-guide

Oligodendrocytes <- c("ENSG00000205927", "ENSG00000184221", "ENSG00000134853", "ENSG00000173546", "ENSG00000177468", "ENSG00000013297", "ENSG00000197971", "ENSG00000204655", "ENSG00000100146")

oliglist <- list()
 
for(i in 1:length(Oligodendrocytes)){
   
   tryCatch({

        p <- VlnPlot(lonza.sub, features = Oligodendrocytes[i])

   oliglist[[i]] <- p

   }, error=function(e){})
}

myplot <- patchwork::wrap_plots(oliglist, nrow=1)

nb_plots <- length(oliglist)
basewidth <- grDevices::dev.size(units = "px")[1]
ggsave(paste(dt,"_TG_LONZA_Oligodendrocytes_Gene_Marker_Violin_Plots.png", sep=""), myplot, width = nb_plots*basewidth*5, units = "px")

So there are two Ensembl IDs that are not present in 'lonza.sub' The above code causes

Error: Only know how to add ggplots and/or grobs
Execution halted

I initially hoped it would work with a error message and so I left that part in from the SO answer for 'Error in R loop' Which gives this error.

ERROR : None of the requested variables were found: ENSG00000184221 
ERROR : None of the requested variables were found: ENSG00000204655 
Error: Only know how to add ggplots and/or grobs
Execution halted

It could be that there is a space. If you know of an easier way, please let me know. Thank you for looking. I hope this helps other people too.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source