title: How to get elementwise means of lists within a list in R
body: <p>I have dataset (<em>my_data</em>) which is a list of length 50. Each of the elements of this list consists of 4 lists of 2 values each, which are generated from a specified bivariate Normal distribution. My goal is to get the means of each of the component from all the lists for the entire data. For instance, I want the mean of the first components of the first lists for all 50 components of the <em>mydata</em> list, the mean of the second components of the first lists for all 50 components of the <em>mydata</em> list, and so on. I have achieved so with the following code.</p>
  <pre><code>set.seed(4991)
  
  mean_list &lt;- list(c(0,0),c(3,3),c(6,6),c(0,0))
  
  #Covariance matrix
  cov_mat &lt;- matrix(c(1, .8, .8, 1), 2)  
  
  my_data &lt;- list()
  
  #50 iterations 
  for (k in 1:50){
    seg_data &lt;- list()
    for (i in 1:4) {
      seg_data[[i]] &lt;- abs(mvrnorm(1, mu = mean_list[[i]], Sigma = cov_mat) )
    }
    my_data[[k]] &lt;- seg_data
  }
  
  
  first_list1 &lt;- c()
  first_list2 &lt;- c()
  second_list1 &lt;- c()
  second_list2&lt;- c()
  third_list1 &lt;- c()
  third_list2 &lt;- c()
  fourth_list1 &lt;- c()
  fourth_list2 &lt;- c()
  
  for (p in 1:length(my_data)) {
    first_list1[p]  &lt;- my_data[[p]][[1]][1]
    first_list2[p]  &lt;- my_data[[p]][[1]][2]
    second_list1[p] &lt;- my_data[[p]][[2]][1]
    second_list2[p] &lt;- my_data[[p]][[2]][2]
    third_list1[p]  &lt;- my_data[[p]][[3]][1]
    third_list2[p]  &lt;- my_data[[p]][[3]][2]
    fourth_list1[p] &lt;- my_data[[p]][[4]][1]
    fourth_list2[p] &lt;- my_data[[p]][[4]][2]
  }
  
  data.frame(first_elements=c(mean(first_list1,na.rm = T),
                              mean(second_list1,na.rm = T),
                              mean(third_list1,na.rm = T),
                              mean(fourth_list1,na.rm = T))
            ,second_elements=c(mean(first_list2,na.rm = T),
                              mean(second_list2,na.rm = T),
                              mean(third_list2,na.rm = T),
                              mean(fourth_list2,na.rm = T))
            ) 
  </code></pre>
  <p>I am having trouble finding an easier way of coding this. I am sure it is possible with <em>dplyr</em> package in R, but have not been able to figure it out yet. Is it possible to find the elementwise means without having to create so many variables?</p>