for loop function in Seurat analysis in R

337 Views Asked by At

I have tried to get multiple outputs of the function I made

ratio_marker_out_2 = function(marker_gene, cluster_id){
marker_gene = list(row.names(FindMarkers(glioblastoma, ident.1 = cluster_id)))
for (gene in marker_gene){
all_cells_all_markers = glioblastoma@assays$RNA@counts[gene,]
selected_cells_all_marker = all_cells_all_markers[cluster_id!=Idents(glioblastoma)]
gene_count_out_cluster = glioblastoma@assays$RNA@counts[,cluster_id!=Idents(glioblastoma)] 
ratio_out = sum(selected_cells_all_marker)/sum(gene_count_out_cluster) 
} 
return(ratio_out)
}

Here, the length of marker_gene is about hundreds. Let's say the length is 100. I want to get ratio_out of each gene in marker_gene. However, when running this function, I only get one output instead of a list of 100 ratio_out. Could please anyone helps how to fix it?

The output I got for

ratio_marker_out_2(marker_gene, 0)

is 1 0.5354895. Please see the pict below enter image description here

2

There are 2 best solutions below

3
On

It can be that sum built-in function.

By default, it returns a number. So when you do:

ratio_out = sum(selected_cells_all_marker)/sum(gene_count_out_cluster)

you're actually dividing two numerics.

So if you want to return a list, you must divide, depending on your calculations, just

ratio_out = (selected_cells_all_marker)/sum(gene_count_out_cluster)
0
On

I have solved this issue using

all_cells_all_markers[marker_gene, cluster_id!=Idents(glioblastoma)]
ratio_out = (selected_cells_all_marker)/sum(gene_count_out_cluster).