File: Data.R

package info (click to toggle)
r-cran-modeltools 0.2-24-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 184 kB
  • sloc: sh: 39; makefile: 2
file content (255 lines) | stat: -rw-r--r-- 7,821 bytes parent folder | download | duplicates (4)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

### Parse and evaluate a formula, return the data as object of class 
### `ModelEnv'

ModelEnvFormula <- function(formula, data = list(), subset = NULL, 
                            na.action = NULL, frame = NULL, 
                            enclos = sys.frame(sys.nframe()),
                            other = list(), designMatrix = TRUE,
                            responseMatrix = TRUE,
                            setHook = NULL, ...)
{
  
    mf <- match.call(expand.dots = FALSE)
    m <- match(c("formula", "data", "subset", "na.action"),
               names(mf), 0)
    mf <- mf[c(1, m)]
    mf[[1]] <- as.name("model.frame")

    ### NA-handling will for the ModelFrame objects later on...
    mf$na.action <- stats::na.pass

    MEF <- new("ModelEnvFormula")
    MEF@formula <- c(ParseFormula(formula, data=data)@formula, other)
    MEF@hooks$set <- setHook
    
    if (is.null(frame)) frame <- parent.frame()

    mf$subset <- try(subset)
    if (inherits(mf$subset, "try-error")) mf$subset <- NULL

    MEF@get <- function(which, data=NULL, frame=parent.frame(), envir = MEF@env)
    {
        if(is.null(data))
            RET <- get(which, envir = envir, inherits=FALSE)
        else{
            oldData <- get(which, envir = envir, inherits=FALSE)
            if (!use.subset) mf$subset <- NULL
            mf$data <- data
            mf$formula <- MEF@formula[[which]]
            RET <- eval(mf, frame, enclos = enclos)
            checkData(oldData, RET)
        }
        return(RET)
    }
    
    MEF@set <- function(which = NULL, data = NULL, frame = parent.frame(),
                        envir = MEF@env)
    {
        if (is.null(which)) which <- names(MEF@formula)
        if (any(duplicated(which)))
            stop("Some model terms used more than once")
        
        for (name in which){
            
            if (length(MEF@formula[[name]]) != 2)
                stop("Invalid formula for ", sQuote(name))
            
            mf$data <- data
            mf$formula <- MEF@formula[[name]]

            if (!use.subset) mf$subset <- NULL
            MF <- eval(mf, frame, enclos = enclos)
            if (exists(name, envir = envir, inherits = FALSE))
                checkData(get(name, envir = envir, inherits = FALSE), MF)
            assign(name, MF, envir = envir)
            mt <- attr(MF, "terms")
            
            ## <FIXME>
            ## maybe we don't want to save input and response
            ## in the cases below?
            ## </FIXME>
            if (name == "input" && designMatrix) {
                assign("designMatrix",
                       model.matrix(mt, data = MF, ...),
                       envir = envir)
            }

            if (name == "response" && responseMatrix) {
                attr(mt, "intercept") <- 0
                assign("responseMatrix",
                       model.matrix(mt, data=MF, ...),
                       envir = envir)
            }
        }
        MEapply(MEF, MEF@hooks$set, clone=FALSE)
    }

    use.subset <- TRUE
    MEF@set(which = NULL, data = data, frame = frame)
    use.subset <- FALSE
    
    ### handle NA's
    if (!is.null(na.action))
        MEF <- na.action(MEF)
    MEF
}

### compare basic properties of two data.frames

checkData <- function(old, new) {

    if (!is.null(old)){
        
        if(!all(names(old) %in% names(new)))
            stop("New data must contain the same columns as the original data")
        
        if (!identical(lapply(old, class), lapply(new[names(old)], class)))
            stop("Classes of new data do not match original data")

        if (!identical(lapply(old, levels), lapply(new[names(old)], levels)))
            stop("Levels in factors of new data do not match original data")
    }
}
  
### parse a formula and return the different pieces as `FormulaParts'
### object

ParseFormula <- function(formula, data = list()) {

    formula <- terms(formula, data = data)
    attributes(formula) <- NULL

    if (length(formula) == 3) {
        fresponse <- formula[c(1,2)]
        frhs <- formula[c(1,3)]
        ### if (frhs[[2]] == "1") frhs <- NULL
    }
  
    if (length(formula) == 2) {
        fresponse <- NULL   
        frhs <- formula
    }
  
    finput <- frhs
    fblocks <- frhs

    ### <FIXME>
    ### will fail for `y ~ . | blocks' constructs
    ### </FIXME>

    if (!is.null(frhs) && length(frhs[[2]]) > 1) {
        if (deparse(frhs[[2]][[1]]) == "|") {
            finput[[2]] <- frhs[[2]][[2]]
            fblocks[[2]] <- frhs[[2]][[3]]
        } else {
            fblocks <- NULL
        }
    } else {
        fblocks <- NULL
    }
  
    RET = new("FormulaParts")
  
    RET@formula$response <- fresponse
    RET@formula$input <- finput
    RET@formula$blocks <- fblocks

    return(RET)
}


###**********************************************************

## A simple model environment where designMatrix and responseMatrix
## are directly specified. Usefull for models without a formula
## interface. This is much more limited than ModelEnvFormula, but can
## be faster because no formula parsing is necessary. The subset
## argument needs to be a indexing vector into the design and response
## matrix, respectively. Funny things may happen if the matrices have
## no column names and the @[gs]et slots are used in combination with
## new data <FIXME>is proper handling of that case possible?</FIXME>

ModelEnvMatrix <- function(designMatrix=NULL, responseMatrix=NULL,
                           subset = NULL, na.action = NULL,
                           other=list(), ...)
{    
    MEM <- new("ModelEnv")

    N <- max(nrow(designMatrix), nrow(responseMatrix))
    
    if(is.null(subset) && N>0) subset <- 1:N
    
    if(!is.null(designMatrix))
        assign("designMatrix",
               as.matrix(designMatrix)[subset,,drop=FALSE],
               envir = MEM@env)
    
    if(!is.null(responseMatrix))
        assign("responseMatrix",
               as.matrix(responseMatrix)[subset,,drop=FALSE],
               envir = MEM@env)

    for(n in names(other)){
        if(is.matrix(other[[n]]))
            assign(n,
                   other[[n]][subset,,drop=FALSE],
                   envir = MEM@env)
        else
            assign(n,
                   other[[n]][subset],
                   envir = MEM@env)
    }
    
    MEM@get <- function(which, data=NULL, frame=NULL, envir = MEM@env)
    {
        if(is.null(data))
            RET <- get(which, envir = envir, inherits=FALSE)
        else
        {    
            if(is.null(colnames(data)))
                colnames(data) <- createColnames(data)
        
            oldNames <- colnames(get(which, envir = envir,
                                     inherits=FALSE))
            RET <- data[,oldNames,drop=FALSE]
        }
        return(RET)
    }
    
    MEM@set <- function(which = NULL, data = NULL, frame=NULL,
                        envir = MEM@env)
    {
        if(is.null(which))
            which <- c("designMatrix", "responseMatrix")
        
        if(is.null(data))
            stop("No data specified")
        
        if (any(duplicated(which)))
            stop("Some model terms used more than once")
        
        if(is.null(colnames(data)))
            colnames(data) <- createColnames(data)
        
        for (name in which){
            
            oldNames <- colnames(get(name, envir = envir,
                                     inherits=FALSE))
            
            assign(name, as.matrix(data[,oldNames,drop=FALSE]),
                   envir = envir)            
        }
    }

    ## handle NA's
    if (!is.null(na.action))
        MEM <- na.action(MEM)
    MEM
}

## Make sure that every matrix has column names
createColnames <- function(data)
{
    paste("V",1:ncol(data),sep=".")
}