Scaling data in R gives a false error. The "center" length should equal the number of columns "x"

I am trying to scale data.frame in the range of 0 and 1 using the following code:

for(i in 1:nrow(data)) { x <- data[i, ] data[i, ] <- scale(x, min(x), max(x)-min(x)) } Data: x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 15 6 6 0 9 3 1 4 5 1 1 13 0 0 20 5 28 2 24 14 7 0 15 7 0 11 3 3 4 15 7 0 30 0 344 3 10 5 2 0 6 2 0 5 0 0 2 7 1 0 11 0 399 4 9 4 2 0 5 2 0 4 0 0 2 6 1 0 10 0 28 5 6 2 1 0 3 1 0 2 0 0 1 3 1 0 6 0 82 6 9 4 2 0 5 2 0 4 0 0 2 6 1 0 10 0 42 

But I get the following error message:

 Error in scale.default(x, min(x), max(x) - min(x)) (from #4) : length of 'center' must equal the number of columns of 'x' 
+6
source share
2 answers

Using this data, your example works for me:

 data <- matrix(sample(1:1000,17*6), ncol=17,nrow=6) for(i in 1:nrow(data)){ x <- data[i, ] data[i, ] <- scale(x, min(x), max(x)-min(x)) } 

Here is another option using a scale, without a loop. You just need to provide the scale and center the same columns as your matrix.

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

EDIT how to access the result.

The scale returns a matrix with 2 attributes. To get the data.frame file, you just need to force the scaling result to data.frame.

 dat.scale <- scale(data, center = mins, scale = maxs - mins) dat.sacle <- as.data.frame(dat.scale) 
+8
source

The center and scale arguments for scale must have a length equal to the number of columns in x . It looks like data is data.frame , so your x has as many columns as your data.frame does and therefore conflict. You can overcome this obstacle in three ways:

  • drop the row into the atomic vector before going to scale (which will consider it as a single column): scale(as.numeric(x), ...)
  • convert data to matrix , which automatically removes row selections into atomic vectors.
  • use the @agstudy apply clause, which will work, be it data.frame or matrix and perhaps the "right" way to do it in R.
+4
source

All Articles