如何将矢量映射到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
我得到零列。 –
你能解释一下你的映射吗?我不明白为什么2映射到62或者为什么270在那里,因为它落在你的范围之外。 – David
对不起@David,我混淆了两个我用来理解问题的例子。它基本上是一个线性映射。 – nachocab
这应该是显而易见的,但这不是一个“R”问题。这是一个关于基本线性代数的问题。 –