Debian Codegraph @

R/dataset-methods.R

raw
1 setValidity("named.list",function(object){
2 if(all(is.na(object@names))) "list is unnamed"
3 else if(length([email protected])!=length(object@names[nzchar(object@names)])){
4 znames <- which(!nzchar(object@names))
5 paste(
6 if(length(znames) == 1) "element" else "elements",
7 paste(znames,collapse=", "),
8 if(length(znames) == 1) "is" else "are",
9 "unnamed"
10 )
11 }
12 else if(length(unique(object@names)) != length(object@names)) paste(
13 "list has duplicate names:",
14 paste(dQuote(object@names[duplicated(object@names)]),collapse=", ")
15 )
16 else TRUE
17 })
18
19 setValidity("data.set",function(object){
20
21 isItemVector <- sapply(object,is,"item.vector")
22 if(!all(isItemVector)) {
23 wrong.els <- object[!isItemVector]
24 wrong.classes <- sapply(wrong.els,class)
25 wrong.names <- object@names[!isItemVector]
26 paste(
27 "object has elements of wrong class:",
28 paste(
29 paste("class(",wrong.names,") = ",wrong.classes,sep=""),
30 collapse=", "
31 )
32 )
33 }
34 else if(any(length(object@row_names) != sapply(object,length))){
35 wrong.els <- object[!isItemVector]
36 wrong.names <- object@names[!isItemVector]
37 wront.lengths <- sapply(object,length)
38 paste(
39 if(length(which(wrong.lengths)) > 1) "elements have" else "element has",
40 "wrong length: ",
41 paste(
42 paste("class(",wrong.names,") = ",wrong.classes,sep=""),
43 collapse=", "
44 ),
45 "where",
46 length(object@row_names),
47 "is required"
48 )
49 }
50 else TRUE
51 })
52
53 setMethod("initialize","named.list",function(.Object,...){
54 args <- list(...)
55 if(is.list(args[[1]])) args <- unclass(args[[1]])
56 [email protected] <- unname(args)
57 .Object@names <- as.character(names(args))
58 if(validObject(.Object)) .Object
59 })
60
61 setMethod("initialize","item.list",function(.Object,...){
62 args <- list(...)
63 if(is.list(args[[1]])) args <- unclass(args[[1]])
64 [email protected] <- unname(lapply(args,as.item))
65 .Object@names <- as.character(names(args))
66 if(validObject(.Object)) .Object
67 })
68
69
70 setMethod("show","named.list",function(object)
71 print.default(unclass(object))
72 )
73
74 setLength <- function(x,n){
75 tmp <- unname(x)
76 length(x) <- n
77 x[] <- tmp
78 attributes(x) <- attributes(tmp)
79 x
80 }
81
82 setMethod("initialize","data.set",function(.Object,...,row.names=NULL,document=character()){
83
84 args <- list(...)
85 if(inherits(args[[1]],"data.frame") && missing(row.names)){
86 row.names <- rownames(args[[1]])
87 }
88 if(is.list(args[[1]])) {
89 args <- unclass(args[[1]])
90 }
91 nr <- max(sapply(args,length))
92 args <- lapply(args,setLength,n=nr)
93 args <- lapply(args,as.item)
94
95 [email protected] <- unname(args)
96 .Object@names <- as.character(names(args))
97
98 if (is.null(row.names))
99 row.names <- seq_len(nr)
100 else {
101 if (is.object(row.names) || !is.integer(row.names))
102 row.names <- as.character(row.names)
103 if (any(is.na(row.names)))
104 stop("row names contain missing values")
105 if (any(duplicated(row.names)))
106 stop("duplicate row.names: ", paste(unique(row.names[duplicated(row.names)]),
107 collapse = ", "))
108 }
109 .Object@row_names <- row.names
110 .Object@document <- document
111
112 if(validObject(.Object)) .Object
113 })
114
115 setAs("data.set","named.list",function(from,to){
116 new(to,structure([email protected],names=from@names))
117 })
118
119 # dim.data.set <- dim.data.frame
120 setMethod("dim","data.set",function(x)
121 c( length(x@row_names),
122 length([email protected])
123 )
124 )
125
126 setMethod("row.names","data.set",function(x){
127 x@row_names
128 })
129
130 setReplaceMethod("row.names","data.set",function(x,value){
131 nr <- length([email protected][[1]])
132 if(is.null(value)){
133 value <- seq_len(nr)
134 }
135 else if(length(value) != nr)
136 stop("invalid 'row.names' given for data set")
137 x@row_names <- value
138 x
139 })
140
141
142 setMethod("dimnames","data.set",function(x)
143 list(x@row_names,x@names))
144
145 setReplaceMethod("dimnames","data.set",function(x,value) {
146 d <- dim(x)
147 if (!is.list(value) || length(value) != 2L)
148 stop("invalid 'dimnames' given for data set")
149 value[[1L]] <- as.character(value[[1L]])
150 value[[2L]] <- as.character(value[[2L]])
151 if (d[[1L]] != length(value[[1L]]) || d[[2L]] != length(value[[2L]]))
152 stop("invalid 'dimnames' given for data set")
153 row.names(x) <- value[[1L]]
154 names(x) <- value[[2L]]
155 x
156 })
157
158
159 setMethod("[",signature(x="data.set",i="atomic",j="atomic",drop="ANY"),
160 function(x,i,j,...,drop=FALSE){
161 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
162 frame <- frame[i,j,drop=drop]
163 if(is.data.frame(frame))
164 new("data.set",
165 unclass(frame),
166 document=x@document
167 )
168 else
169 frame
170 })
171
172 setMethod("[",signature(x="data.set",i="atomic",j="missing",drop="ANY"),
173 function(x,i,j,...,drop=FALSE){
174 # cat("\ndata.set,atomic,missing\n")
175 Narg <- nargs()-!missing(drop)
176 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
177 if(Narg > 2){
178 frame <- frame[i,,drop=drop]
179 if(!is.data.frame(frame))
180 frame
181 else
182 new("data.set",
183 unclass(frame),
184 document=x@document
185 )
186 }
187 else {
188 frame <- frame[i]
189 if(!is.data.frame(frame))
190 frame
191 else
192 new("data.set",
193 unclass(frame),
194 document=x@document
195 )
196 }
197 })
198
199 setMethod("[",signature(x="data.set",i="missing",j="atomic",drop="ANY"),
200 function(x,i,j,...,drop=FALSE){
201 # cat("\ndata.set,missing,atomic\n")
202 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
203 frame <- frame[,j,drop=drop]
204 if(is.data.frame(frame))
205 new("data.set",
206 unclass(frame),
207 document=x@document
208 )
209 else
210 frame
211 })
212
213 setMethod("[",signature(x="data.set",i="missing",j="missing",drop="ANY"),
214 function(x,i,j,...,drop=FALSE){
215 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
216 frame <- frame[,,drop=drop]
217 if(is.data.frame(frame))
218 new("data.set",
219 unclass(frame),
220 document=x@document
221 )
222 else
223 frame
224 })
225
226
227 setReplaceMethod("[",signature(x="data.set",i="ANY",j="ANY",value="ANY"),
228 function(x,i,j,value){
229 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
230 frame[i,j] <- value
231 new("data.set",
232 unclass(frame),
233 document=x@document
234 )
235 })
236
237
238
239 "[[<-.data.set" <- function(x,...,value){
240 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
241 frame[[...]] <- value
242 new("data.set",
243 unclass(frame),
244 document=x@document
245 )
246 }
247
248 as.list.data.set <- function(x,...)structure([email protected],names=x@names)
249
250 as.data.frame.data.set <- function(x, row.names = NULL, optional = FALSE, ...){
251 as.data.frame(as.list(x),
252 row.names=if(length(row.names)) rownames
253 else x@row_names,
254 optional=optional)
255 }
256
257
258
259 data.set <- function(..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
260 stringsAsFactors = FALSE,
261 document = NULL){
262
263 args <- list(...)
264 if(!length(names(args))){
265
266 subst <- substitute(list(...))
267 names(args) <- as.character(subst[-1])
268 }
269 argn <- names(args)
270 args <- lapply(seq_along(args),function(i){
271 x <- args[[i]]
272 n <- names(args)[[i]]
273 if(is(x,"item.vector"))
274 structure(list(x),class="data.frame",row.names=seq_len(length(x)),names=n)
275 else if(is(x,"data.set"))
276 structure(as.list(x),class="data.frame",row.names=x@row_names)
277 else x
278 })
279 names(args) <- argn
280 frame <- do.call(data.frame,
281 c(args,
282 row.names=row.names,
283 check.rows=check.rows,
284 check.names=check.names,
285 stringsAsFactors=stringsAsFactors
286 ))
287 new("data.set",
288 frame,
289 document=as.character(document)
290 )
291 }
292
293
294 setMethod("annotation","data.set",function(x){
295 d <- lapply(x,annotation)
296 if(length(d))
297 structure(d,names=x@names,class="annotation.list")
298 else NULL
299 })
300
301
302 format.data.set <- function(x,...){
303 y <- structure([email protected],
304 row.names=x@row_names,
305 names=x@names,
306 class="data.frame")
307 y[] <- lapply(y[],format,justify="right")
308 y
309 }
310 #setMethod("format","data.set",format.data.set)
311
312 print.data.set <- function(x,max.obs=Inf,width=Inf,...){
313 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
314 print_frame_internal(frame,max.obs=max.obs,width=width,...)
315 }
316
317 print_frame_internal <- function(x,max.obs=Inf,width=Inf,...){
318 if(is.finite(max.obs)){
319 if(nrow(x)<=max.obs)
320 {
321 max.obs <- Inf
322 res <- x
323 }
324 else
325 res <- x[seq_len(max.obs),,drop=FALSE]
326 }
327 else
328 res <- x
329
330 varn <- names(res)
331 rown <- rownames(res)
332
333 res <- lapply(res,format)
334 res <- mapply(c,varn,res)
335 res <- apply(res,2,format,justify="right")
336 res <- apply(cbind(c("",rown),res),2,format,justify="right")
337
338 if(is.finite(width) && ncol(res)){
339
340 ww <- cumsum(nchar(res[1,])+1)-1
341 if(any(ww > width)){
342
343 keep <- which(ww < width - 3)
344 res <- cbind(res[,keep],"...")
345 }
346 }
347
348 if(is.finite(max.obs) && nrow(res)){
349
350 mkdots <- function(n) paste(rep(".",n),collapse="")
351 ww <- nchar(res[1,])
352 res <- rbind(res,sapply(ww,mkdots))
353 res <- apply(res,1,paste,collapse=" ")
354 res <- c(res,paste("(",length(res)-2," of ",nrow(x)," observations shown)",sep=""))
355 }
356 else
357 res <- apply(res,1,paste,collapse=" ")
358
359 writeLines(res)
360 }
361
362 setMethod("show","data.set",function(object){
363 cat("\nData set with",nrow(object),"observations and",ncol(object),"variables\n\n")
364 print.data.set(object,max.obs=getOption("show.max.obs"),width=getOption("width"))
365 })
366
367 setMethod("print","data.set",function(x,...)print.data.set(x,...))
368
369 # summary.data.set <- summary.data.frame
370
371 is.data.set <- function(x) is(x,"data.set")
372
373 str.data.set <- function (object, ...)
374 {
375 cat("Data set ","with ", nrow(object), " obs. of ", (p <- ncol(object)),
376 " variable", if (p != 1)
377 "s", if (p > 0)
378 ":", "\n", sep = "")
379 object <- structure(as.list(object),class="data.frame")
380 if (length(l <- list(...)) && any("give.length" == names(l)))
381 invisible(NextMethod("str", ...))
382 else invisible(NextMethod("str", give.length = FALSE, ...))
383 }
384
385 subset.data.set <- function (x, subset, select, drop = FALSE, ...)
386 {
387 r <- if (missing(subset))
388 rep_len(TRUE, nrow(x))
389 else {
390 e <- substitute(subset)
391 r <- eval(e, x, parent.frame())
392 if (!is.logical(r))
393 stop("'subset' must be logical")
394 r & !is.na(r)
395 }
396 vars <- if (missing(select))
397 rep_len(TRUE, ncol(x))
398 else {
399 nl <- as.list(seq_along(x))
400 names(nl) <- names(x)
401 eval(substitute(select), nl, parent.frame())
402 }
403 x[r, vars, drop = drop]
404 }
405
406
407
408 setMethod("within","data.set",function (data, expr, ...)
409 {
410 parent <- parent.frame()
411 encl <- new.env(parent=parent)
412 frame <- structure([email protected],row.names=data@row_names,names=data@names,class="data.frame")
413 nr <- nrow(frame)
414 rn <- row.names(frame)
415 assign("N_",nr,envir=encl)
416 e <- evalq(environment(), frame, encl)
417 ret <- eval(substitute(expr), e)
418 l <- rev(as.list(e))
419
420 length1 <- sapply(l,length) == 1
421 if(any(length1)){
422 ii <- which(length1)
423 for(i in ii){
424 l[[i]] <- rep(l[[i]],nr)
425 }
426 }
427
428 wrong.length <- sapply(l,length) != nr
429 if(any(wrong.length)){
430 warning("Variables ",paste(sQuote(names(l)[wrong.length]),collapse=","),
431 " have wrong length, removing them.")
432 l[wrong.length] <- NULL
433 }
434 coercable <- sapply(l,is.atomic) | sapply(l,is.factor)
435 items <- sapply(l,is,"item")
436 if(any(!items & coercable))
437 l[!items & coercable] <- lapply(l[!items & coercable],as.item)
438 if(any(!items & !coercable)){
439 warning("Cannot change variables ",paste(sQuote(names(l)[!items & !coercable]),collapse=","),
440 " into items, removing them.")
441 l[!items & !coercable] <- NULL
442 }
443 frame[names(l)] <- l
444 use <- names(frame) %in% names(l)
445 frame <- frame[use]
446 row.names(frame) <- rn
447 new("data.set",
448 frame,
449 document=data@document)
450 })
451
452 cbind.data.set <- function (..., deparse.level = 1)
453 data.set(..., check.names = FALSE)
454
455 setMethod("description","data.set",function(x){
456 res <- lapply(x,description)
457 structure(res,class="descriptions")
458 })
459 print.descriptions <- function(x,quote=FALSE,...){
460 Write.descriptions(x,file=stdout())
461 }
462
463 Write.descriptions <- function(x,file=stdout(),...){
464 x <- sapply(x,function(des){
465 if(length(des)) sQuote(des)
466 else " (none) "
467 })
468 out <- c(
469 "",
470 paste("",format(names(x),justify="left"),format(x,justify="left")),
471 ""
472 )
473 writeLines(out,con=file)
474 }
475
476 as.data.frame.descriptions <- function(x,...){
477 data.frame(variable=names(x),
478 description=as.character(x))
479 }
480
481 setMethod("unique","data.set",function(x, incomparables = FALSE, ...){
482 frame <- structure([email protected],row.names=x@row_names,names=x@names,class="data.frame")
483 new("data.set",
484 unique(frame,incomparables=incomparables,...),
485 document=x@document
486 )
487 })
488
489
490 fapply.data.set <- function(formula,data,...)
491 fapply.default(formula,data=as.data.frame(data,optional=TRUE),...)
492
493 setMethod("as.data.set","list",function(x,row.names=NULL,...){
494 n_row <- unique(sapply(x,length))
495 if(length(n_row)>1)
496 stop("list elements must have same length")
497 class(x) <- "data.frame"
498 if(length(row.names)){
499 if(length(row.names)!=nrow(x)) stop("row.names argument has wrong length")
500 attr(x,"row.names") <- row.names
501 }
502 else
503 attr(x,"row.names") <- 1:n_row
504 new("data.set",x)
505 })
506
507
508
509 setMethod("merge",signature(x="data.set","data.set"),function(x,y,...){
510 x <- new("data.frame",as.list(x),row.names=x@row_names)
511 y <- new("data.frame",as.list(y),row.names=y@row_names)
512 z <- merge(x,y,...)
513 new("data.set",z)
514 })
515
516 setMethod("merge",signature(x="data.set","data.frame"),function(x,y,...){
517 x <- new("data.frame",as.list(x),row.names=x@row_names)
518 z <- merge(x,y,...)
519 new("data.set",z)
520 })
521
522 setMethod("merge",signature(x="data.frame","data.set"),function(x,y,...){
523 y <- new("data.frame",as.list(y),row.names=y@row_names)
524 z <- merge(x,y,...)
525 new("data.set",z)
526 })
527
528 setMethod("rbind2",signature(x="data.set",y="data.set"),function(x,y){
529 x <- asS4(new("data.frame",as.list(x),row.names=x@row_names),FALSE)
530 y <- asS4(new("data.frame",as.list(y),row.names=y@row_names),FALSE)
531 z <- rbind(x,y)
532 new("data.set",z)
533 })
534
535 setMethod("rbind2",signature(x="data.set",y="data.frame"),function(x,y){
536 x <- asS4(new("data.frame",as.list(x),row.names=x@row_names),FALSE)
537 z <- cbind(x,y)
538 new("data.set",z)
539 })
540
541 setMethod("cbind2",signature(x="data.set",y="data.set"),function(x,y){
542 x <- asS4(new("data.frame",as.list(x),row.names=x@row_names),FALSE)
543 y <- asS4(new("data.frame",as.list(y),row.names=y@row_names),FALSE)
544 z <- cbind(x,y)
545 new("data.set",z)
546 })
547
548 setMethod("cbind2",signature(x="data.frame",y="data.set"),function(x,y){
549 y <- asS4(new("data.frame",as.list(y),row.names=y@row_names),FALSE)
550 z <- cbind(x,y)
551 new("data.set",z)
552 })
553
554 setMethod("cbind2",signature(x="data.set",y="data.frame"),function(x,y){
555 x <- asS4(new("data.frame",as.list(x),row.names=x@row_names),FALSE)
556 z <- cbind(x,y)
557 new("data.set",z)
558 })
559
560 rbind.data.set <- function(...,deparse.level=1){
561 args <- list(...)
562 to.data.frame <- function(x){
563 if(inherits(x,"data.set"))
564 structure(
565 [email protected],
566 names=x@names,
567 row.names=x@row_names,
568 class="data.frame"
569 )
570 else as.data.frame(x)
571 }
572 args <- lapply(args,to.data.frame)
573 res <- do.call("rbind",c(args,list(deparse.level=deparse.level)))
574 new("data.set",res,row.names=row.names(res))
575 }
576
577 dsView <- function(x){
578
579 title <- paste("Data set:", deparse(substitute(x))[1])
580
581 Data <- lapply([email protected],format,justify="left")
582
583 document <- x@document
584 row.names <- x@row_names
585 .names <- x@names
586 frame <- structure(Data,row.names=row.names,names=x@names,
587 class="data.frame")
588 for(n in names(frame)){
589 d <- description(x[[n]])
590 if(length(d))
591 attr(frame[[n]],"label") <- d
592 }
593
594 View.call <- call("View",x=frame,title=title)
595 eval(View.call,globalenv())
596 #View(x=frame,title=title)
597 # do.call("View",list(x=frame,title=title))
598 }
599
600
601 ## Copied and modified from 'summary.R' of the package 'base'.
602 ## The original copyright notice says:
603 ## """
604 ## File src/library/base/R/summary.R
605 ## Part of the R package, https://www.R-project.org
606 ##
607 ## Copyright (C) 1995-2022 The R Core Team
608 ##
609 ## This program is free software; you can redistribute it and/or modify
610 ## it under the terms of the GNU General Public License as published by
611 ## the Free Software Foundation; either version 2 of the License, or
612 ## (at your option) any later version.
613 ## """
614
615 setMethod("summary","data.set",
616 function(object, maxsum = 7, digits = max(3, getOption("digits") -3), ...){
617 z <- lapply(as.list(object), summary, maxsum = maxsum, digits = 12,
618 ...)
619 nv <- length(object)
620 nm <- names(object)
621 lw <- numeric(nv)
622 nr <- max(unlist(lapply(z, NROW)))
623 for (i in 1:nv) {
624 sms <- z[[i]]
625 if (is.matrix(sms)) {
626 cn <- paste(nm[i], gsub("^ +", "", colnames(sms)),
627 sep = ".")
628 tmp <- format(sms)
629 if (nrow(sms) < nr)
630 tmp <- rbind(tmp, matrix("", nr - nrow(sms),
631 ncol(sms)))
632 sms <- apply(tmp, 1, function(x) paste(x, collapse = " "))
633 wid <- sapply(tmp[1, ], nchar, type = "w")
634 blanks <- paste(character(max(wid)), collapse = " ")
635 pad0 <- floor((wid - nchar(cn, type = "w"))/2)
636 pad1 <- wid - nchar(cn, type = "w") - pad0
637 cn <- paste(substring(blanks, 1, pad0), cn, substring(blanks,
638 1, pad1), sep = "")
639 nm[i] <- paste(cn, collapse = " ")
640 z[[i]] <- sms
641 }
642 else {
643 lbs <- format(names(sms))
644 sms <- paste(lbs, ":", format(sms, digits = digits),
645 " ", sep = "")
646 lw[i] <- nchar(lbs[1], type = "w")
647 length(sms) <- nr
648 z[[i]] <- sms
649 }
650 }
651 z <- unlist(z, use.names = TRUE)
652 dim(z) <- c(nr, nv)
653 blanks <- paste(character(max(lw) + 2), collapse = " ")
654 pad <- floor(lw - nchar(nm, type = "w")/2)
655 nm <- paste(substring(blanks, 1, pad), nm, sep = "")
656 dimnames(z) <- list(rep.int("", nr), nm)
657 attr(z, "class") <- c("table")
658 z
659 })
660
661 ## as.list() method
662 as.list.item.list <- function(x,...)structure([email protected],names=x@names)
663
664 setMethod("head",signature(x="data.set"),
665 function(x,n=20,...){
666 y <- utils::head.matrix(x,n=n,...)
667 rownames(y) <- rownames(x)[1:n]
668 return(y)
669 })
670 setMethod("tail",signature(x="data.set"),
671 function(x,n=20,...){
672 y <- utils::tail.matrix(x,n=n,...)
673 rownames(y) <- rownames(x)[seq.int(to=nrow(x),length.out=n)]
674 return(y)
675 })
676
677
678 as.data.table.data.set <- function(x, ...){
679 dataf <- as.data.frame(as.list(x),
680 row.names=if(length(row.names)) rownames
681 else x@row_names)
682 as.data.table(dataf,...)
683 }
684