R 在 -1 和 1 之间缩放向量

R Scaling a vector between -1 and 1

我有一个包含 100 个元素的向量。

vec <- c(58.12, 51.97, 61.83, 53.46, 30.67, 38.8, 48.79, 56.82, 20.19, 
53.1, 54.95, 46.45, 41.09, 51.76, 52.56, 44.63, 52.95, 30, 50.7, 
56.33, 64.72, 39.99, 39.37, 33.82, 47.62, 51.28, 37.38, 50.55, 
68.39, 53.88, 33.37, 29.69, 30.74, 47.51, 72.64, 47.88, 42.28, 
62.71, 47.47, 71.45, 55.94, 39.5, 32.97, 28.81, 56.59, 49.79, 
43.49, 41.97, 43.61, 30.09, 50.18, 63.88, 57.77, 41.57, 27.52, 
38.47, 46.13, 41.85, 39.14, 46.38, 47.73, 61.51, 66.73, 56.28, 
59.89, 47.38, 27.27, 17.41, 36.8, 27.21, 43.13, 43.68, 29.33, 
53.76, 74.69, 29.56, 63.41, 31.61, 56.32, 49.68, 48.65, 46.81, 
51.23, 65.23, 54.79, 84.64, 63.55, 32.4, 47.93, 68.13, 33.05, 
30.21, 40.62, 48.28, 38.69, 31.72, 52.01, 64.17, 53.12, 35.03)

我想缩放这个向量 vec 以便 0 到 50 之间的所有数字都从 -1 缩放到 0 并且 50 到 100 之间的所有数字都从 0 缩放到 1。

我写了下面的代码来做到这一点 -

newvec = ifelse(vec < 50, -(vec/min(vec, na.rm = T)), vec/max(vec, na.rm = T))
plot(vec, newvec)

输出看起来像(见黑色圆圈)-

对于大于 50 的数字,缩放很好,但是,对于小于 50 的数字,缩放以相反的顺序工作并且不正确(如图所示)。

我在这张图中画了一条红线,显示了正确的缩放比例。

谁能告诉我我做错了什么?

谢谢。

看起来像一个完美的线性方程!

m <- lm(  y~x, data=data.frame( x=c(0,50,100), y=c(-1,0,1) ) )
coef(m)

给出:

(Intercept)           x 
      -1.00        0.02 

所以乘以0.02减去1

您可以先将其重新调整为 0-1,然后乘以二再减一:

vec <- c(58.12, 51.97, 61.83, 53.46, 30.67, 38.8, 48.79, 56.82, 20.19, 
         53.1, 54.95, 46.45, 41.09, 51.76, 52.56, 44.63, 52.95, 30, 50.7, 
         56.33, 64.72, 39.99, 39.37, 33.82, 47.62, 51.28, 37.38, 50.55, 
         68.39, 53.88, 33.37, 29.69, 30.74, 47.51, 72.64, 47.88, 42.28, 
         62.71, 47.47, 71.45, 55.94, 39.5, 32.97, 28.81, 56.59, 49.79, 
         43.49, 41.97, 43.61, 30.09, 50.18, 63.88, 57.77, 41.57, 27.52, 
         38.47, 46.13, 41.85, 39.14, 46.38, 47.73, 61.51, 66.73, 56.28, 
         59.89, 47.38, 27.27, 17.41, 36.8, 27.21, 43.13, 43.68, 29.33, 
         53.76, 74.69, 29.56, 63.41, 31.61, 56.32, 49.68, 48.65, 46.81, 
         51.23, 65.23, 54.79, 84.64, 63.55, 32.4, 47.93, 68.13, 33.05, 
         30.21, 40.62, 48.28, 38.69, 31.72, 52.01, 64.17, 53.12, 35.03)


rescale_minMax <- function(x){
  1 - (x - max(x)) / (min(x) - max(x)) 
}

newvec = rescale_minMax(vec) * 2 - 1
plot(vec, newvec)

reprex package (v0.3.0)

于 2021 年 3 月 12 日创建