Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying "dim" function over elements of a list in R

Tags:

list

r

I have n number of lists, lets say list1, list2, ..., listn. Each list has 10 elements and I need to calculate the "mean" of "dim" of ten elements of each list. So the output should be a vector of length n.

For example the first element of the output vector should be:

n1 = mean(dim(list1[[1]]), dim(list1[[2]]), dim(list1[[3]]), ..., dim(list1[[10]]) 

I know how to obtain it using for-loops but I am sure it is not the best solution.

The lists have structure derived from one of "Bioconductor" R packages called "edgeR". So each element of the list has this structure:

 $ :Formal class 'TopTags' [package "edgeR"] with 1 slots
  .. ..@ .Data:List of 4
  .. .. ..$ :'data.frame':      2608 obs. of  4 variables:
  .. .. .. ..$ logFC : num [1:2608] 6.37 -6.48 -5.72 -5.6 -4.01 ...
  .. .. .. ..$ logCPM: num [1:2608] 5.1 2.55 2.08 1.57 3.08 ...
  .. .. .. ..$ PValue: num [1:2608] 3.16e-292 1.57e-187 2.15e-152 5.58e-141 1.27e-135 ...
  .. .. .. ..$ FDR   : num [1:2608] 7.37e-288 1.83e-183 1.67e-148 3.25e-137 5.92e-132 ...
  .. .. ..$ : chr "BH"
  .. .. ..$ : chr [1:2] "healthy" "cancerous"
  .. .. ..$ : chr "exact"

And since each list has 10 elements, I have 10 repeats of above structure when running:

str(list1)
like image 612
hora Avatar asked Jan 13 '23 15:01

hora


1 Answers

Original question

lapply (or sapply) is your friend:

mean(sapply(mylist,dim))

If you have many lists with a uniform meaning and structure, you should use instead a list of lists (i.e., mylist[[3]] instead of mylist3).

Edited question

sapply(mylist, function(x) mean(sapply(x,dim)))

will return a vector of means of inner lists.

Question in a comment

If your list contains matrices instead of vectors and you want to average one of the dimensions (dim(.)[1] or dim(.)[2]), you can use ncol and nrow for that instead of dim.

Alternatively, you can pass any function there, e.g.,

sapply(mylist, function(x) mean(sapply(x, function(y) sum(dim(y)))))

to average the sums of dimensions.

like image 181
sds Avatar answered Jan 22 '23 06:01

sds