luciano
luciano

Reputation: 13850

Why does scale produce a matrix?

scale seems like a useful function with the exception that it produces a matrix from a numeric vector like so:

class(scale(mtcars$drat))
# [1] "matrix"

Is there a function that produces a numeric vector without having to do something like as.numeric(scale(x))?

Upvotes: 6

Views: 1660

Answers (2)

Roland
Roland

Reputation: 132969

I don't see the problem, but you could simply use this:

res <- (mtcars$drat-mean(mtcars$drat, na.rm=TRUE))/sd(mtcars$drat, na.rm=TRUE)
res[1:3]
#[1] 0.5675137 0.5675137 0.4739996

Or write your own methods:

scale.numeric <- scale.integer <- function (x, center = TRUE, scale = TRUE) {
  if (is.logical(center)) {
    if (center) {
      center <- mean(x, na.rm = TRUE)
      x <- x-center
    }
  }
  else if (is.numeric(center) && (length(center) == 1)) 
    x <- x-center
  else stop("invalid value for center")
  if (is.logical(scale)) {
    if (scale) {
      f <- function(v) {
        v <- v[!is.na(v)]
        sqrt(sum(v^2)/max(1, length(v) - 1L))
      }
      scale <- f(x)
      x <- x/scale
    }
  }
  if (is.numeric(center)) 
    attr(x, "scaled:center") <- center
  if (is.numeric(scale)) 
    attr(x, "scaled:scale") <- scale
  x
}

res <- scale(mtcars$drat)
res[1:3]
#[1] 0.5675137 0.5675137 0.4739996
class(res)
#[1] "numeric"

Or, a bit shorter, but slightly less efficient:

scale.numeric <- scale.integer <- function (x, center = TRUE, scale = TRUE) {
  res <- scale.default(x, center, scale)
  dim(res) <- NULL
  res
}

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

The help page for ?scale says:

scale is generic function whose default method centers and/or scales the columns of a numeric matrix.

When a vector is used as an argument, it is treated like one-column matrix. Hence, the function returns a matrix.

You can convert the matrix to a vector with, e.g., as.vector, but for a lot of cases you can operate with the one-column matrix like you would operate with a vector.

Upvotes: 5

Related Questions