使用值 0 到 1 缩放 R 中的数字矩阵 [英] Scaling a numeric matrix in R with values 0 to 1

查看:40
本文介绍了使用值 0 到 1 缩放 R 中的数字矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我所拥有的数字矩阵的摘录

Here is an excerpt of numeric matrix that I have

 [1,]   30 -33.129487   3894754.1 -39.701738 -38.356477 -34.220534
 [2,]   29 -44.289487  -8217525.9 -44.801738 -47.946477 -41.020534
 [3,]   28 -48.439487  -4572815.9 -49.181738 -48.086477 -46.110534
 [4,]   27 -48.359487  -2454575.9 -42.031738 -43.706477 -43.900534
 [5,]   26 -38.919487  -2157535.9 -47.881738 -43.576477 -46.330534
 [6,]   25 -45.069487  -5122485.9 -47.831738 -47.156477 -42.860534
 [7,]   24 -46.207487  -2336325.9 -53.131738 -50.576477 -50.410534
 [8,]   23 -51.127487  -2637685.9 -43.121738 -47.336477 -47.040534
 [9,]   22 -45.645487   3700424.1 -56.151738 -47.396477 -50.720534
[10,]   21 -56.739487   1572594.1 -49.831738 -54.386577 -52.470534
[11,]   20 -46.319487    642214.1 -39.631738 -44.406577 -41.490534

我现在想要做的是将每列的值缩放为从 0 到 1 的值.

What I want to do now, is to scale the values for each column to have values from 0 to 1.

我尝试使用矩阵上的 scale() 函数(默认参数)来完成此操作,我得到了这个

I tried to accomplish this using the scale() function on my matrix (default parameters), and I got this

[1,] -0.88123100  0.53812440 -1.05963281 -1.031191482 -0.92872324
 [2,] -1.17808251 -1.13538649 -1.19575096 -1.289013031 -1.11327085
 [3,] -1.28847084 -0.63180980 -1.31265244 -1.292776849 -1.25141017
 [4,] -1.28634287 -0.33914007 -1.12182012 -1.175023107 -1.19143220
 [5,] -1.03524267 -0.29809911 -1.27795565 -1.171528133 -1.25738083
 [6,] -1.19883019 -0.70775576 -1.27662116 -1.267774342 -1.16320727
 [7,] -1.22910054 -0.32280189 -1.41807728 -1.359719044 -1.36810940
 [8,] -1.35997055 -0.36443973 -1.15091204 -1.272613537 -1.27664977
 [9,] -1.21415156  0.51127451 -1.49868058 -1.274226602 -1.37652260
[10,] -1.50924749  0.21727976 -1.33000083 -1.462151358 -1.42401647
[11,] -1.23207969  0.08873245 -1.05776452 -1.193844887 -1.12602635

这已经接近我想要的了,但是 0:1 的值甚至更好.我阅读了 scale() 的帮助手册,但我真的不明白我该怎么做.

Which is already close to what I want, but values from 0:1 were even better. I read the help manual of scale(), but I really don't understand how I would do that.

推荐答案

尝试以下看起来很简单的方法:

Try the following, which seems simple enough:

## Data to make a minimal reproducible example
m <- matrix(rnorm(9), ncol=3)

## Rescale each column to range between 0 and 1
apply(m, MARGIN = 2, FUN = function(X) (X - min(X))/diff(range(X)))
#           [,1]      [,2]      [,3]
# [1,] 0.0000000 0.0000000 0.5220198
# [2,] 0.6239273 1.0000000 0.0000000
# [3,] 1.0000000 0.9253893 1.0000000

这篇关于使用值 0 到 1 缩放 R 中的数字矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆