【问题标题】:Scaling data in R, resulting in error: "length of 'center' must equal the number of columns of 'x'"在R中缩放数据,导致错误:“'center'的长度必须等于'x'的列数”
【发布时间】:2016-04-20 15:08:30
【问题描述】:

我正在尝试使用以下代码从 ISLR 缩放 Hitters 数据:

data = Hitters
apply(data,2,function(x) sum(is.na(x)))
data = subset(data, !is.na(Salary))
apply(data,2,function(x) sum(is.na(x)))

maxs <- apply(data, 2, max) 
mins <- apply(data, 2, min)

scaled <- as.data.frame(scale(data, center = mins, scale = maxs - mins))

其中,我从thisR-Bloggers 神经网络教程中提取(我正在尝试使用 NN 为 Hitters 数据中的薪水建立一个预测模型)。但是,我不断收到错误消息:

> scale(data, center = mins, scale = maxs - mins)
Error in scale.default(data, center = mins, scale = maxs - mins) : 
  length of 'center' must equal the number of columns of 'x'

我在 Stackoverflow 上阅读了有关此比例函数错误 here 的讨论,但不明白为什么我会收到此错误,因为 maxs 和 mins 与我的矩阵具有相同的列,即 Hitters 数据。

【问题讨论】:

  • 你的最大值和最小值的结果都是字符。在scale 中如何使用这些值?
  • 您尝试最大/最小的一些值是字符变量。联赛、分区、新联赛...
  • LeagueDivisionNewLeague 都是因子。这导致结果变成字符串。

标签: r neural-network scale


【解决方案1】:

如果您删除非数字列,它会起作用...

data = Hitters
apply(data,2,function(x) sum(is.na(x)))
data = subset(data, !is.na(Salary))
apply(data,2,function(x) sum(is.na(x)))

# add this line to remove non-numeric columns.
data <- data[, sapply(data, is.numeric)]

maxs <- as.numeric(apply(data, 2, max) )
mins <- as.numeric(apply(data, 2, min))

scaled <- as.data.frame(scale(data, center = mins, scale = maxs - mins))

【讨论】:

  • 感谢您的回复@cory,所以您不能将比例函数与因子一起使用?
  • 缩放“联赛”变量意味着什么?是文字。这是关于缩放或标准化变量的作用以及为什么要这样做的一个很好的答案...stats.stackexchange.com/questions/7112/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多