0

This should be an easy question... I'm looking to scale a numeric vector to a specified mean and range.

For instance, I would like to scale a vector, x, to mean = 1, min = 0, and max = 2. Here's my vector x, with min = 0, max = 1:

> x <- runif(100, 0, 1)
> mean(x)
[1] 0.4897899

My first thought was to scale to a mean = 0, using scale(), and add 1... But this doesn't address the issue of the range:

> mean(scale(x)+1)
[1] 1

But, this results in negative values:

> sum((scale(x)+1) < 0)
[1] 21

My next thought was to use scales::rescale(), but it appears to only have arguments for setting the desired range.

This seems like an easy question, but I'm stumped! Any help would be greatly appreciated.

-Alex.

  • 3
    Not easy: actually impossible in general. If you don't want to distort the scale of the values (i.e. if you are limiting to yourself to **affine transformations** where you're allowed to add/subtract a constant and/or multiply/divide by a scaling constant), you can't in general satisfy three criteria simultaneously (min, max, *and* mean) – Ben Bolker Jan 27 '21 at 00:59
  • Thank you, Dr. Bolker. Now that you mention it, it seems so obvious! Perhaps I was asking the wrong question. By some strange coincidence, I'm actually trying to follow your previous advice about using frequency weights in glmm models. You mentioned scaling the weights to mean = 1. I assumed weights must be non-zero, so I've been trying to scale my weights vector to a mean = 1 and *at least* a min = 0. Maybe I should repost this question, but could you advise how best to scale frequency weights? – J. Alex Baecher Jan 27 '21 at 01:33
  • 1
    Assuming you have a vector of weights `w` that are **all non-negative** to begin with `all(w>=0)`, then `w2 <- w/mean(w)` should do the trick. (Proof: `mean(w2) == mean(w/mean(w)) == mean(w)/mean(w) == 1`). Assuming your weights aren't all zero to begin with (which would be weird), the mean will be positive, so the rescaled weights will be non-negative and have mean 1, which is all you need. – Ben Bolker Jan 27 '21 at 01:35
  • So simple. Thank you. As always, you're help is much appreciated. – J. Alex Baecher Jan 27 '21 at 01:39
  • it's mildly cheesy, but you could rewrite this question to focus on your original question ("I have arbitrary weights, I want to convert them to frequency weights") and then answer your own question ... – Ben Bolker Jan 28 '21 at 00:01

0 Answers0