botloggy
botloggy

Reputation: 403

How to get the average of vectors in lists having same names inside for loop in R

Here is the small example of what i am trying to do.

ex1 <- c(1,2,3)
nm <- c("cone","ctwo","cthree") 
names(ex1) <- nm

ex2 <- c(1.3,1.5,1.6)
names(ex2) <- nm

ex3 <- c(1.4,1.6,1.8)
names(ex3) <- nm

ex <- list(ex1,ex2,ex3)

for (i in seq(ex))
{
   ab<- ex[[i]]
}

The output i am getting is:

  ab
  cone   ctwo cthree 
  1.4    1.6    1.8

But the expected output should be something like this.

  ab
  cone   ctwo cthree 
  1.233    1.7    2.133

It gives the average values of cone ctwo and cthree from the three vectors in the list.

Upvotes: 1

Views: 62

Answers (4)

akrun
akrun

Reputation: 886948

We can use colMeans after rbinding the list elements

colMeans(do.call(rbind, ex))
#    cone     ctwo   cthree 
#1.233333 1.700000 2.133333 

If we have objects created in the global environment with name starting with 'ex' followed by numbers, get all of them in a list with mget and then apply the code as above

colMeans(do.call(rbind, mget(ls(pattern = "ex\\d+")))) 

Or using Reduce

Reduce(`+`, ex)/length(ex)

Or using a for loop

n <- length(ex)
v1 <- numeric(n)
for(i in seq_along(ex)) v1 <- v1 + ex[[i]]
v1/m

Upvotes: 4

NelsonGon
NelsonGon

Reputation: 13309

Perhaps computationally slow but we can use plyr:

 sapply(plyr::ldply(ex),mean)
    cone     ctwo   cthree 
1.233333 1.700000 2.133333 

Upvotes: 2

yarnabrina
yarnabrina

Reputation: 1656

Another way will be this:

> rowMeans(data.frame(ex))
    cone     ctwo   cthree 
1.233333 1.700000 2.133333

Upvotes: 3

Paul
Paul

Reputation: 2959

Name your list elements in ex:

ex <- list(ex1 = ex1, ex2 = ex2, ex3 = ex3)

then find the mean row-wise:

apply(as.data.frame(ex), 1, mean)

    cone     ctwo   cthree 
1.233333 1.700000 2.133333 

Upvotes: 2

Related Questions