Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset out all elements with the same name of list

Tags:

r

Data

I have a list of lists that looks something like this:

sublist1 <- list(power=as.matrix(c(rnorm(10)),c(rnorm)),x=rnorm(10),y=rnorm(10))
sublist2 <- list(power=as.matrix(c(rnorm(10)),c(rnorm)),x=rnorm(10),y=rnorm(10))
sublist3 <- list(power=as.matrix(c(rnorm(10)),c(rnorm)),x=rnorm(10),y=rnorm(10))
mylist = list(sublist1,sublist2,sublist3)

My goal would be to pull out only the matrices named power

I've tried

mylist_power =mylist[sapply(mylist, '[', 'Power')]

But thats not working.

Brownie point alert!!!

How can I find the mean of the newly created list of matrices named power?

like image 473
Ted Mosby Avatar asked Sep 03 '25 14:09

Ted Mosby


1 Answers

mylist_power <- sapply(mylist, '[', 'power')

and some means:

sapply(mylist_power, mean) # one per matrix
sapply(mylist_power, colMeans) # for each column and each matrix
sapply(mylist_power, rowMeans) # for each row and each matrix
mean(unlist(mylist_power)) # for the whole list
Reduce(`+`, mylist_power) / length(mylist_power) # element-wise
like image 81
Julius Vainora Avatar answered Sep 05 '25 11:09

Julius Vainora