File: recode.R

package info (click to toggle)
r-cran-memisc 0.99.31.8.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,136 kB
  • sloc: ansic: 5,117; makefile: 2
file content (323 lines) | stat: -rw-r--r-- 12,166 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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
setGeneric("recode", function(x,...,
                              copy=getOption("recode_copy",identical(otherwise,"copy")),
                              otherwise=NA) standardGeneric("recode"))
setMethod("recode","item",function(x,...,
                                   copy=getOption("recode_copy",identical(otherwise,"copy")),
                                   otherwise=NA){
  recodings <- match.call(expand.dots=FALSE)$...
  recodings <- recodings[nzchar(sapply(recodings,paste,collapse=""))]
  if(length(otherwise)!=1) stop("otherwise= argument must have length 1")
  
  if(any(sapply(sapply(recodings,"[[",1),paste)!="<-"))
    stop("invalid recoding request")
  if(!length(recodings)) return(x)
  newcodes <- lapply(recodings,"[[",2)
  conditions <- lapply(recodings,"[[",3)
  has.range <- paste(lapply(conditions,"[[",1)) == "range"
  if(any(has.range)){
    oldcodes <- conditions
    has.min <- paste(lapply(conditions[has.range],"[[",2)) == "min"
    has.max <- paste(lapply(conditions[has.range],"[[",3)) == "max"
    if(any(has.min)){
      min.list <- list(min=min(x))
      conditions[has.range][has.min] <- lapply(
                conditions[has.range][has.min],
                function(x) do.call("substitute",list(x,min.list))
                )
    }
    if(any(has.max)){
      max.list <- list(max=max(x))
      conditions[has.range][has.max] <- lapply(
                conditions[has.range][has.max],
                function(x) do.call("substitute",list(x,max.list))
                )
    }
  }
  else
      oldcodes <- sapply(conditions,eval)
  NA_recoded <- any(unlist(suppressWarnings(sapply(oldcodes,is.na))))
      
  conditions[has.range] <- lapply(conditions[has.range],
                          function(x)
                          as.call(list(as.symbol("&"),
                            as.call(list(as.symbol("<="),x[[2]],quote(x@.Data))),
                            as.call(list(as.symbol("<="),quote(x@.Data),x[[3]]))
                            )
                          ))
  conditions[!has.range] <- lapply(conditions[!has.range],
                          function(x)
                          as.call(list(as.symbol("%in%"),quote(x@.Data),x))
                          )
  torecode <- sapply(conditions,eval,envir=environment(),enclos=parent.frame())
  if(!is.matrix(torecode)) torecode <- t(torecode)
  newcodes <- sapply(newcodes,eval,parent.frame())
  nevtrue <- colSums(torecode) == 0
  if(any(nevtrue)){
    nrecng <- paste(recodings[nevtrue])
    if(length(nrecng)>1)
      warning("recodings ",paste(nrecng,collapse=", ")," have no consequences")
    else
      warning("recoding ",nrecng," has no consequences")
  }
  ambiguous <- rowSums(torecode) > 1
  if(any(ambiguous))
    stop("recoding request is ambiguous")
  #y <- if(is.character(newcodes)) as.character(x) else x
  y <- x
  labels(y) <- NULL
  if(is.character(newcodes) && is.numeric(y)) {
    newcodes <- structure(
      seq_along(newcodes),
      names=newcodes
      )
  }
  #newcodes <- newcodes[!nevtrue]
  #torecode <- torecode[,!nevtrue,drop=FALSE]
  for(i in seq(along=newcodes)){
    if(!nevtrue[i])
      y[torecode[,i]] <- as.vector(newcodes[i],mode=storage.mode(y))
  }
  if(!copy){
    recoded <- as.logical(rowSums(torecode))
    tmp <- as.vector(otherwise,mode=storage.mode(y))
    length(otherwise) <- length(y)
    otherwise[] <- tmp
    y[!recoded] <- otherwise[!recoded]
    nNA <-sum(is.na(otherwise[!recoded])) - sum(is.na(x[!recoded]))
    if(nNA > 0)
      warning("recoding created ",nNA," NAs")
    if(!NA_recoded)
      y[is.na(x)] <- NA
}
  newvlab <- newcodes[nzchar(names(newcodes))]
  bijective <- FALSE
  lab.y <- lab.x <- labels(x)
  if(!is.list(oldcodes)){
      # This happens only in one-to-one recodings
      if(length(oldcodes) == length(newcodes) &&
          all(oldcodes %in% newcodes)){
          if(copy) bijective <- TRUE
          else if(length(lab.x) && all(lab.x@values %in% oldcodes))
              bijective <- TRUE
      }
  }
  if(length(lab.x) && bijective && !length(names(newcodes))){
      ii <- match(oldcodes,lab.x@values)
      jj <- match(newcodes,lab.y@values)
      lab.y@.Data[jj] <- lab.x@.Data[ii]
      labels(y) <- lab.y
  }
  else if(length(lab.x) && copy){
    lab.y.val <- lab.y@values
    lab.oldcodes <- lapply(conditions,Substitute,list(x=lab.y.val))
    lab.torecode <- sapply(lab.oldcodes,eval,envir=environment(),enclos=parent.frame())
    for(i in seq(along=newcodes)){
      lab.y.val[lab.torecode[,i]] <- as.vector(newcodes[i],mode=storage.mode(lab.y.val))
    }
    lab.y.val <- sort(unique(lab.y.val))
    ii <- match(lab.y.val,lab.y@values)
    lab.y.lab <- lab.y@.Data[ii]
    labels(y) <- new("value.labels",lab.y.lab,values=lab.y.val)
    if(length(newvlab))
      labels(y) <- labels(y) + newvlab
  }
  else if(length(newvlab)){
    if(length(names(otherwise)))
      newvlab <- new("value.labels",names(newvlab),values=newvlab) + otherwise
    labels(y) <- newvlab
    if(measurement(y) %in% c("interval","ratio"))
        measurement(y) <- "nominal"
  }
#   else if(length(newvlab)){
#     if(identical(otherwise,"copy"))
#       labels(y) <- labels(y) + newvlab
#     else
#       labels(y) <- newvlab
#     }

  return(y)
})

setMethod("recode","vector",function(x,...,
                                     copy=getOption("recode_copy",identical(otherwise,"copy")),
                                     otherwise=NA){
    call <- match.call()

    if(length(otherwise)!=1) stop("otherwise= argument must have length 1")

    if("recodes" %in% names(call)
       || is.character(call[[3]])
       ) {
        return(car_recode(var=x,...))
    }
    recodings <- match.call(expand.dots=FALSE)$...
    if("to.factor" %in% names(recodings)
       && is.logical(recodings[["to.factor"]])
       ) {
        warning("'to.factor' argument no longer in use")
        recodings["to.factor"] <- NULL
    }
    recodings <- recodings[nzchar(sapply(recodings,paste,collapse=""))]
    if(any(sapply(sapply(recodings,"[[",1),paste)!="<-"))
        stop("invalid recoding request")

    if(!length(recodings)) return(x)
    newcodes <- lapply(recodings,"[[",2)
    oldcodes <- lapply(recodings,"[[",3)
    NA_recoded <- any(unlist(suppressWarnings(sapply(oldcodes,is.na))))
    has.range <- paste(lapply(oldcodes,"[[",1)) == "range"
    if(any(has.range)){
        has.min <- paste(lapply(oldcodes[has.range],"[[",2)) == "min"
        has.max <- paste(lapply(oldcodes[has.range],"[[",3)) == "max"
        if(any(has.min)){
            min.list <- list(min=min(x, na.rm=TRUE))
            oldcodes[has.range][has.min] <- lapply(
                oldcodes[has.range][has.min],
                function(x) do.call("substitute",list(x,min.list))
            )
        }
        if(any(has.max)){
            max.list <- list(max=max(x, na.rm=TRUE))
            oldcodes[has.range][has.max] <- lapply(
                oldcodes[has.range][has.max],
                function(x) do.call("substitute",list(x,max.list))
            )
        }
    }
    oldcodes[has.range] <- lapply(oldcodes[has.range],
                                  function(x)
                                      as.call(list(as.symbol("&"),
                                                   as.call(list(as.symbol("<="),x[[2]],as.symbol("x"))),
                                                   as.call(list(as.symbol("<="),as.symbol("x"),x[[3]]))
                                                   )
                                              ))
    oldcodes[!has.range] <- lapply(oldcodes[!has.range],
                                   function(x)
                                       as.call(list(as.symbol("%in%"),as.symbol("x"),x))
                                   )
    torecode <- sapply(oldcodes,eval,envir=environment())
    if(!is.matrix(torecode)) torecode <- t(torecode)
    newcodes <- sapply(newcodes,eval,parent.frame())
    nevtrue <- colSums(torecode, na.rm=TRUE) == 0
    if(any(nevtrue)){
        nrecng <- paste(recodings[nevtrue])
        if(length(nrecng)>1)
            warning("recodings ",paste(nrecng,collapse=", ")," have no consequences")
        else
            warning("recoding ",nrecng," has no consequences")
    }
    ambiguous <- rowSums(torecode, na.rm=TRUE) > 1
    if(any(ambiguous))
        stop("recoding request is ambiguous")
    y <- if(is.character(newcodes)) as.character(x) else x
    newcodes <- newcodes[!nevtrue]
    torecode <- torecode[,!nevtrue,drop=FALSE]
    for(i in seq(along=newcodes)){
        y[torecode[,i]] <- newcodes[i]
    }
    if(!copy){
        if(is.character(otherwise)) newcodes <- c(newcodes, otherwise)
        recoded <- as.logical(rowSums(torecode))
        recoded[is.na(recoded)] <- TRUE
        tmp <- as.vector(otherwise,mode=storage.mode(y))
        length(otherwise) <- length(y)
        otherwise[] <- tmp
        y[!recoded] <- otherwise[!recoded]
        nNA <- sum(is.na(otherwise[!recoded])) - sum(is.na(x[!recoded]))
        if(nNA > 0)
            warning("recoding created ",nNA," NAs")
        if(!NA_recoded)
            y[is.na(x)] <- NA
    }
    if(is.character(y)) {
        levels <- sort(unique(y[y%nin%newcodes]))
        levels <- c(newcodes,levels)
        y <- factor(y,levels=levels)
    }
    return(y)
})

setMethod("recode","factor",function(x,...,copy=getOption("recode_copy",identical(otherwise,"copy")),
                                     otherwise=NA){
  recodings <- match.call(expand.dots=FALSE)$...

  if(length(otherwise)!=1) stop("otherwise= argument must have length 1")

  if("to.factor" %in% names(recodings)
    && is.logical(recodings[["to.factor"]])
    ) {
      warning("'to.factor' argument no longer in use")
      recodings["to.factor"] <- NULL
    }
  recodings <- recodings[nzchar(sapply(recodings,paste,collapse=""))]
  if(any(sapply(sapply(recodings,"[[",1),paste)!="<-"))
    stop("invalid recoding request")

  if(!length(recodings)) return(x)
  newcodes <- sapply(recodings,"[[",2)
  if(copy)
      newcodes <- as.character(newcodes) # 'copy=TRUE' requires the result also to be a factor ... 
  if(is.character(newcodes))
      to_factor <- TRUE
  else
      to_factor <- FALSE
  oldcodes <- lapply(recodings,"[[",3)
  oldcodes <- lapply(oldcodes,eval,envir=environment())
  torecode <- sapply(oldcodes,function(o) x %in% o)
  if(!is.matrix(torecode)) torecode <- t(torecode)
  nevtrue <- colSums(torecode) == 0
  if(any(nevtrue)){
    nrecng <- paste(recodings[nevtrue])
    if(length(nrecng)>1)
      warning("recodings ",paste(nrecng,collapse=", ")," have no consequences")
    else
      warning("recoding ",nrecng," has no consequences")
  }
  ambiguous <- rowSums(torecode) > 1
  if(any(ambiguous))
    stop("recoding request is ambiguous")

  if(to_factor){
      y <- integer(length=length(x))
      for(i in 1:ncol(torecode)){
          y[torecode[,i]] <- i
      }
      if(copy){
          olevels <- levels(unique(x[y==0,drop=TRUE]))
          max.y <- max(y)
          for(i in seq(along=olevels)){
              y[x == olevels[i]] <- max.y + i
          }
          y <- factor(y,levels=1:max(y),labels=c(newcodes,olevels))
      }
      else if(is.character(otherwise)){
          max.y <- max(y)
          y[y == 0] <- max.y + 1
          y <- factor(y,levels=1:max(y),labels=c(newcodes,otherwise[1]))
      }
      else {
          y <- factor(y,levels=1:max(y),labels=newcodes)
          recoded <- as.logical(rowSums(torecode))
          nNA <- sum(is.na(y[!recoded]) & !is.na(x[!recoded]))
          if(nNA > 0)
              warning("recoding created ",nNA," NAs")
      }
  }
  else {
      y <- vector(mode=storage.mode(newcodes),
                  length=length(x))
      for(i in 1:ncol(torecode))
          y[torecode[,i]] <- newcodes[i]
      recoded <- as.logical(rowSums(torecode))
      recoded[is.na(recoded)] <- TRUE
      tmp <- as.vector(otherwise,mode=storage.mode(y))
      length(otherwise) <- length(y)
      otherwise[] <- tmp
      y[!recoded] <- otherwise[!recoded]      
      nNA <- sum(is.na(y[!recoded]) & !is.na(x[!recoded]))
      if(nNA > 0)
          warning("recoding created ",nNA," NAs")
  }
  return(y)
})