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)
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
).
sapply(mylist, function(x) mean(sapply(x,dim)))
will return a vector of means of inner lists.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With