在两点之间缩放系列
如何缩放一个系列,使该系列中的第一个数字为 0,最后一个数字为 1。我研究了“近似”、“缩放”,但它们没有实现此目标。
# generate series from exponential distr
s = sort(rexp(100))
# scale/interpolate 's' such that it starts at 0 and ends at 1?
# approx(s)
# scale(s)
How do I scale a series such that the first number in the series is 0 and last number is 1. I looked into 'approx', 'scale' but they do not achieve this objective.
# generate series from exponential distr
s = sort(rexp(100))
# scale/interpolate 's' such that it starts at 0 and ends at 1?
# approx(s)
# scale(s)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
scales
包有一个函数可以为您执行此操作:rescale
。默认情况下,这会将给定的
s
范围缩放到 0 到 1,但其中一个或两个都可以调整。例如,如果您希望它从 0 缩放到 10,或者您希望将
s
的最大值缩放为 1,但为 0(而不是s
的最小值) )缩放到0,你可以使用The
scales
package has a function that will do this for you:rescale
.By default, this scales the given range of
s
onto 0 to 1, but either or both of those can be adjusted. For example, if you wanted it scaled from 0 to 10,or if you wanted the largest value of
s
scaled to 1, but 0 (instead of the smallest value ofs
) scaled to 0, you could use使用基本算术创建一个小函数来执行此操作很简单:
It's straight-forward to create a small function to do this using basic arithmetic:
或者:(
未经测试)
它具有将原始居中和缩放因子作为属性附加到输出的功能,因此可以检索它们并在以后用于取消缩放数据(如果需要)。它有一个奇怪的地方,即它总是以(按列)矩阵的形式返回结果,即使它传递的是一个向量;如果您想要一个向量而不是矩阵,可以使用 drop(scale(...))(这通常并不重要,但矩阵格式有时会引起问题)下游......根据我的经验,更常见的是 tibbles/tidyverse,尽管我没有停下来检查这些情况下到底出了什么问题)。
Alternatively:
(untested)
This has the feature that it attaches the original centering and scaling factors to the output as attributes, so they can be retrieved and used to un-scale the data later (if desired). It has the oddity that it always returns the result as a (columnwise) matrix, even if it was passed a vector; you can use
drop(scale(...))
if you want a vector instead of a matrix (this usually doesn't matter but the matrix format can occasionally cause trouble downstream ... in my experience more often with tibbles/in tidyverse, although I haven't stopped to examine exactly what's going wrong in these cases).这应该可以做到:
编辑
我对这两种方法的性能很好奇
从
reshape::rescaler.default
中提取原始代码会产生类似的结果。
This should do it:
EDIT
I was curious about the performance of the two methods
Extracting the raw code from
reshape::rescaler.default
Yields similar result.
您还可以使用插入符号包,它将为您提供 preProcess 功能,就像这样简单:
更多详细信息请参阅 软件包帮助。
You can also make use of the caret package which will provide you the preProcess function which is just simple like this:
More details on the package help.
我在 r 中创建了以下函数:
这里,第一个是起点,最后一个是终点。
I created following function in r:
Here, first is start point, last is end point.