Mike
Mike

Reputation: 1069

Finding the mean of a subset of a matrix

I'm struggling with something quite simple. I am trying to find the mean of a subset of a matrix. For example, I would like to find the mean of the last 196 elements of each row in a matrix.

My code looks as follows:

for (i in 1:length(ratios))  
{  
    mean(ratios[length(ratios[,1])-196:length(ratios[,1]),i])  
} 

Any help would be appreciated!

Upvotes: 1

Views: 1137

Answers (2)

Mike
Mike

Reputation: 1069

I've actually just worked it out. For some reason you need to insert brackets around the row part of the ratio matrix as follows:

for (i in 1:length(ratios)){  
  mean(ratios[(length(ratios[,1])-196):length(ratios[,1]),i])  
}

Hope this helps anyone with similar problems

Upvotes: 0

Jilber Urbina
Jilber Urbina

Reputation: 61164

This is a more direct approach

>rowMeans(tail(ratios, 196))

tail(ratios, 196) returns the last 196 elements of each row of ratios, and rowMeans calculates the mean for each row.

In your axample, you are taking col means, intead of row meas, so try:

>colMeans(tail(ratios,10))

Here's an example

> ratios <- iris[, sapply(iris, is.numeric)]
> Means <- numeric(ncol(ratios))

> for (i in 1:length(ratios))
  {
    Means[i] <- (mean(ratios[(length(ratios[,1])-10):length(ratios[,1]),i]))
 }

> COLMeans <- colMeans(tail(ratios,10))

> Means  ## Using `for` loop
[1] 6.490909 3.036364 5.336364 2.163636

> COLMeans # using `tail` and `colMeans`
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
        6.45         3.03         5.33         2.17 

Upvotes: 2

Related Questions