我有一个名为spam的数据集,其中包含58列和约3500行与垃圾邮件相关的数据。

我计划将来在这个数据集上运行一些线性回归,但我想事先做一些预处理,并将列标准化,使其具有零平均值和单位方差。

有人告诉我,最好的方法是用R,所以我想问,如何用R实现归一化?我已经正确加载了数据,我只是在寻找一些包或方法来执行这个任务。


当前回答

我假设你想要的是均值为0,标准差为1。如果你的数据在一个数据框架中,所有的列都是数值的,你可以简单地调用数据上的缩放函数来做你想做的事情。

dat <- data.frame(x = rnorm(10, 30, .2), y = runif(10, 3, 5))
scaled.dat <- scale(dat)

# check that we get mean of 0 and sd of 1
colMeans(scaled.dat)  # faster version of apply(scaled.dat, 2, mean)
apply(scaled.dat, 2, sd)

使用内置函数是有品位的。比如这只猫:

其他回答

折叠包提供了最快的缩放函数-在c++中使用Welfords在线算法实现:

dat <- data.frame(x = rnorm(1e6, 30, .2), 
                  y = runif(1e6, 3, 5),
                  z = runif(1e6, 10, 20))

library(collapse)
library(microbenchmark)
microbenchmark(fscale(dat), scale(dat))

Unit: milliseconds
        expr       min       lq      mean    median        uq      max neval cld
 fscale(dat)  27.86456  29.5864  38.96896  30.80421  43.79045 313.5729   100  a 
  scale(dat) 357.07130 391.0914 489.93546 416.33626 625.38561 793.2243   100   b

此外:fscale是S3通用的向量、矩阵和数据帧,还支持分组和/或加权缩放操作,以及缩放到任意均值和标准偏差。

使用“recommderlab”包。下载并安装软件包。 这个包内置了一个命令“Normalize”。它还允许你从众多归一化方法中选择一种即"中心"或" z分数" 请参考以下示例:

## create a matrix with ratings
m <- matrix(sample(c(NA,0:5),50, replace=TRUE, prob=c(.5,rep(.5/6,6))),nrow=5, ncol=10, dimnames = list(users=paste('u', 1:5, sep=&rdquo;), items=paste('i', 1:10, sep=&rdquo;)))

## do normalization
r <- as(m, "realRatingMatrix")
#here, 'centre' is the default method
r_n1 <- normalize(r) 
#here "Z-score" is the used method used
r_n2 <- normalize(r, method="Z-score")

r
r_n1
r_n2

## show normalized data
image(r, main="Raw Data")
image(r_n1, main="Centered")
image(r_n2, main="Z-Score Normalization")

@BBKim给出了最好的答案,但它可以做得更短。我很惊讶居然还没人想到。

<- data.frame(x = rnorm(10,30, .2), y = runif(10,3,5)) 应用(dat, 2, function(x) (x - mean(x)) / sd(x))

我假设你想要的是均值为0,标准差为1。如果你的数据在一个数据框架中,所有的列都是数值的,你可以简单地调用数据上的缩放函数来做你想做的事情。

dat <- data.frame(x = rnorm(10, 30, .2), y = runif(10, 3, 5))
scaled.dat <- scale(dat)

# check that we get mean of 0 and sd of 1
colMeans(scaled.dat)  # faster version of apply(scaled.dat, 2, mean)
apply(scaled.dat, 2, sd)

使用内置函数是有品位的。比如这只猫:

这是三年前的。不过,我还是觉得有必要补充以下几点:

最常见的归一化是z变换,其中减去平均值并除以变量的标准差。结果将是mean=0, sd=1。

为此,你不需要任何包装。

zVar <- (myVar - mean(myVar)) / sd(myVar)

就是这样。