for loop in R to calculate mean from list

Viewed 8813

This post is on cross validated too and I was directed to post here.

I have a list called d that contains values in R.

> d
$`2017-07-15:10:09:22`
[1] 3.125 4.375 2.500 0.625 5.000 3.750 1.875 1.250

$`2017-07-15:10:10:04`
[1] 0.625 3.750 3.125 1.875 1.250 4.375 2.500 5.000

$`2017-07-15:11:45:45`
[1] 4.375 3.125 3.750 2.500 5.000 1.875 1.250 0.625

I am interested in calculating Mean value of these points and save it to a data frame. So, i made a for loop to do this

l2 <- length(d)
for(j in 1:6)
{
      df$Mean[j] <- (d[[1]][j] 
            + d[[2]][j] + d[[3]][j])/l2 

}

And the length of the list d gets bigger every time. I would like to make this for loop to calculate the mean on its own. Like this..

l2 <- length(d)   
for(j in 1:6)
       {
              df$Mean[j] <- (d[[1]][j] 
                    + d[[2]][j] + d[[3]][j] + d[[4]][j] + ....
               )/l2 

        }

how to make loop of this one to do automatically? Thank You.

2 Answers
Related