I have dataset (my_data) 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 mydata list, the mean of the second components of the first lists for all 50 components of the mydata list, and so on. I have achieved so with the following code.
set.seed(4991)
mean_list <- list(c(0,0),c(3,3),c(6,6),c(0,0))
#Covariance matrix
cov_mat <- matrix(c(1, .8, .8, 1), 2)
my_data <- list()
#50 iterations
for (k in 1:50){
seg_data <- list()
for (i in 1:4) {
seg_data[[i]] <- abs(mvrnorm(1, mu = mean_list[[i]], Sigma = cov_mat) )
}
my_data[[k]] <- seg_data
}
first_list1 <- c()
first_list2 <- c()
second_list1 <- c()
second_list2<- c()
third_list1 <- c()
third_list2 <- c()
fourth_list1 <- c()
fourth_list2 <- c()
for (p in 1:length(my_data)) {
first_list1[p] <- my_data[[p]][[1]][1]
first_list2[p] <- my_data[[p]][[1]][2]
second_list1[p] <- my_data[[p]][[2]][1]
second_list2[p] <- my_data[[p]][[2]][2]
third_list1[p] <- my_data[[p]][[3]][1]
third_list2[p] <- my_data[[p]][[3]][2]
fourth_list1[p] <- my_data[[p]][[4]][1]
fourth_list2[p] <- 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))
)
I am having trouble finding an easier way of coding this. I am sure it is possible with dplyr 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?