File: data_scale_df.R

package info (click to toggle)
r-cran-doby 4.7.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,400 kB
  • sloc: makefile: 2
file content (48 lines) | stat: -rw-r--r-- 1,500 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#' @title Scale numeric variables in a data frame
#'
#' @description Applies `base::scale()` to numeric, integer, or
#'     logical columns in a data frame. Non-numeric columns are left
#'     unchanged.
#' @concept data_handling
#' @param x A data frame or matrix.
#' @param center Logical; if TRUE, center the variables.
#' @param scale Logical; if TRUE, scale the variables.
#'
#' @details
#' If `x` is not a data frame, `base::scale()` is applied directly.
#'
#' @return An object of the same class as `x`.
#'
#' @examples
#' scale_df(iris)
#'
#' @name scale_df
#' @export
scale_df <- function(x, center = TRUE, scale = TRUE){

    if (!is(x, "data.frame")){
        return(scale(x, center=center, scale=scale))
    } else { ## x is dataframe
        
        b <- sapply(x,
                    function(z){is(z, c("numeric")) || is(z, c("integer")) || is(z, c("logical")) })
        
        if (!any(b)){ ## x only has numeric values
            return(scale(x, center=center, scale=scale))
        } else { ## x is dataframe with non-numerics
            
            x2 <- x[,b, drop=FALSE]
            x2 <- scale(x2, center=center, scale=scale)
            x[, b] <- x2
            
            if (!is.null(a <- attributes(x2)$"scaled:center"))
                attr(x, "scaled:center") <- a
            
            if (!is.null(a <- attributes(x2)$"scaled:scale"))
                attr(x, "scaled:scale") <- a
            
            return(x)            
        }            
    }
}