如何将矢量映射到R中的不同范围?

如何将矢量映射到R中的不同范围?

问题描述:

我在范围[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”问题。这是一个关于基本线性代数的问题。 –

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

+0

@Masi,你是什么意思的时间行为?我想'all.dat'是我答案中的符号'x'。那么从','到',你预期的产出和你所得到的是什么? – Julius

+0

我得到零列。 –