Domanda

I'm trying to calculate the weighted average of a statistic sample (vector) in R using this form:

form

The function takes a vector and the weight is adjusted according by a second parameter (1 - 3), which are:

weights

where s is the standard deviation.

I've adjusted the weight accordingly if the parameter is 1 or 3 using else-if's, but I'm having trouble with the 2nd one given that there is criteria to meet...

I've been calculating X - xBar as a vector: m = x-mean(x)

I've been calculating s with an R function: s = sd(x)

My query is regarding how "the meeting of the conditions should be programmed" in the 2nd critera. So far I have an if for each condition, but...

When calculating the weighted average, (taking the top one as an eg), does each element of the x vector (m/s) need to be less than 1? or do I need to test each element and assign a weight from the 3 conditions accordingly?

eg. if the first elements answer was less than 1, assign a weight or 1, but second elements answer was inbetween 1 and 2, assign it a weight of 0.5?

I hope this makes sense. In R it throws a warning message saying the logic is only comparing the first element of the vector... so thats what raised the question.

Thanks in advance.

È stato utile?

Soluzione

To avoid the warning message while staying reasonably efficient, you probably want to use ifelse rather than if and else, perhaps in something like

m <- mean(x)
s <- sd(x)
absstandardx <- abs( (x - m) / s )
w2 <- ifelse( absstandardx < 1, 1, ifelse( absstandardx < 2, 0.5, 0 ) ) 
weightedmean2 <- sum(w2 * x) / sum(w2)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top