Debian Codegraph @

R/simplifyTypes.R

raw
1
2 simplifyTypes <- function(x,verbose=TRUE,...){
3 if(!is.data.frame(x) && !is.data.set(x)) stop("first arg. should be a data.frame or data.set")
4 attr.x <- attributes(x)
5 y <- list()
6 for(i in seq_along(x)){
7 y[[i]] <- simplifyType(x[[i]])
8 if(verbose && typeof(y[[i]])!=typeof(x[[i]])) message("Changed type of variable ",
9 names(x)[i],
10 " from ",
11 sQuote(typeof(x[[i]])),
12 " to ",
13 sQuote(typeof(y[[i]])))
14 }
15 attributes(y) <- attr.x
16 y
17 }
18
19 simplifyType <- function(x) UseMethod("simplifyType")
20 simplifyType.default <- function(x) x
21 simplifyType.double <- function(x){
22 ok <- is.finite(x)
23 #y <- as.integer(x)
24 if(all(x[ok]==trunc(x[ok]))) as.integer(x) else x
25 }
26 simplifyType.labelled <- function(x){
27 if(typeof(x) %in% c("integer","character")) return(x)
28 ok <- is.finite(x)
29 if(any(x[ok]!=trunc(x[ok]))) return(x)
30 y <- x
31 attributes(y) <- NULL
32 y <- as.integer(y)
33 attributes(y) <- attributes(x)
34 if(length(cds <- attr(y,"labels"))){
35 clab <- names(cds)
36 cds <- as.integer(cds)
37 names(cds) <- clab
38 attr(y,"labels") <- cds
39 }
40 if(length(msg <- attr(y,"missing.values"))){
41 if(length(msg$values)) msg$values <- as.integer(msg$values)
42 #if(length(msg$range)) msg$range[is.finite(msg$range)] <- as.integer(msg$range)
43 attr(y,"missing.values") <- msg
44 }
45 y
46 }