Ignacio
Ignacio

Reputation: 7928

Calculate Weighted Arithmetic Mean with a loop?

In R I can use weighted.meanto calculate the Weighted Arithmetic Mean. For example:

wt <- c(5,  5,  4,  1)/15
x <- c(3.7,3.3,3.5,2.8)
xm <- weighted.mean(x, wt)
xm
[1] 3.453333

I can calculate this "by hand": wt[1]*x[1]+wt[2]*x[2]+wt[3]*x[3]+wt[4]*x[4]

I would like to write a loop to do the same. I wrote this code:

xm <-0
for(j in length(wt)){
    xm <- xm + wt[j]*x[j]
}
xm
[1] 0.1866667

What am I doing wrong?

Upvotes: 1

Views: 969

Answers (2)

josliber
josliber

Reputation: 44320

No need for a loop:

sum(wt*x)
# [1] 3.453333

In R is it more efficient and typically less typing (one line instead of 5 in this case) for you to use vectorized functions like sum instead of looping with simple arithmetic operations.

Upvotes: 5

Andrelrms
Andrelrms

Reputation: 819

You just forgot the 1:length(wt)

xm <-0
for(j in 1:length(wt)){
xm <- xm + wt[j]*x[j]
}
xm
[1] 3.453333

Upvotes: 3

Related Questions