Kousalya Devi
Kousalya Devi

Reputation: 13

How to use gsub inside mapply to assign names to Seurat objects

I have three list of files which should be read and used in the CreateSeuratObject function of Seurat package.

I wanted to assign the name of the matrix file after substituting the suffix to the corresponding Seurat object that is created.

I wrote the function for multiple files as below:

  read_atac <- function(sc_matrix, sc_frag, sc_meta){
  
  name <-gsub('filtered_peak_bc_matrix.h5','',sc_matrix)
  
  counts <- Read10X_h5(filename = sc_matrix)
  
  chrom_assay <- CreateChromatinAssay(
    counts = counts,
    sep = c(":", "-"),
    genome = 'hg38',
    fragments = sc_frag,
    min.cells = 10,
    min.features = 200
  )
  
  meta <- read.csv(
    file = sc_meta, 
    header = TRUE, 
    row.names = 1)
  
 assign(name, CreateSeuratObject(counts = chrom_assay, assay = "peaks", meta.data = meta)) 
  
}

mapply(read_atac, sc_matrix, sc_frag, sc_meta)

But, Seurat objects are created with the full name of the matrix file. gsub is not working.

$`GSM8002547_Chr-Veh_R1_filtered_peak_bc_matrix.h5`
An object of class Seurat 
268284 features across 4316 samples within 1 assay 
Active assay: peaks (268284 features, 0 variable features)
 2 layers present: counts, data

I want object names as only 'GSM8002547_Chr-Veh_R1', 'GSM8002548_Chr-Veh_R2' and so on

sc_matrix has a list of matrix files

> sc_matrix
[1] "GSM8002547_Chr-Veh_R1_filtered_peak_bc_matrix.h5"
[2] "GSM8002548_Chr-Veh_R2_filtered_peak_bc_matrix.h5"
[3] "GSM8002549_Veh-Veh_R1_filtered_peak_bc_matrix.h5"
[4] "GSM8002550_Veh-Veh_R2_filtered_peak_bc_matrix.h5"

Upvotes: 0

Views: 43

Answers (1)

Kousalya Devi
Kousalya Devi

Reputation: 13

I found the answer

I stored the output of mapply to a variable 'seurat_list'. Then I used for loop to assign() names to individual objects

# assign names to seurat object list obtained from previous step
    for (i in 1:length(sc_matrix)){
      name <-gsub('_filtered_peak_bc_matrix.h5','_seurat',sc_matrix[i])
      assign(name, seurat_list[i])
      }

Upvotes: 0

Related Questions