2013-08-18 62 views
12

我在範圍[1,10]如何將矢量映射到R中的不同範圍?

c(1,2,9,10) 

一個載體,我想將它映射到一個不同的範圍,例如[12,102]

c(12,22,92,102) 

有R中已經做了這樣的功能?

+0

你能解釋一下你的映射嗎?我不明白爲什麼2映射到62或者爲什麼270在那裏,因爲它落在你的範圍之外。 – David

+0

對不起@David,我混淆了兩個我用來理解問題的例子。它基本上是一個線性映射。 – nachocab

+0

這應該是顯而易見的,但這不是一個「R」問題。這是一個關於基本線性代數的問題。 –

回答

15
linMap <- function(x, from, to) 
    (x - min(x))/max(x - min(x)) * (to - from) + from 

linMap(vec, 12, 102) 
# [1] 12 22 92 102 

或者更明確:用包scales

linMap <- function(x, from, to) { 
    # Shifting the vector so that min(x) == 0 
    x <- x - min(x) 
    # Scaling to the range of [0, 1] 
    x <- x/max(x) 
    # Scaling to the needed amplitude 
    x <- x * (to - from) 
    # Shifting to the needed level 
    x + from 
} 

rescale(vec, c(12, 102))作品。也可以按照@flodel的建議以巧妙的方式利用approxfun

linMap <- function(x, a, b) approxfun(range(x), c(a, b))(x) 
+0

我在你的'linMap'和'rescale'中有一個暫時的行爲,其中一些列在R 3.3.2中變爲零。示例值all.dat < - c(2274959,1531001)'。你知道爲什麼嗎? –

+0

@Masi,你是什麼意思的時間行爲?我想'all.dat'是我答案中的符號'x'。那麼從','到',你預期的產出和你所得到的是什麼? – Julius

+0

我得到零列。 –