procmod_frame.R 16.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#' @include internals.R
NULL

#' Internal function repeating a matrix.
#'
#' @description repeats several times the rows of a matrix
#'              to create a new matrix with more rows. The
#'              final row count must be a multiple of the
#'              initial row count
#'
#' @param x  The matrix to replicate
#' @param nrow  an interger value specifying the number of row
#'                    of the returned matrix
#'
#' @return a new matrix with the same number of columns but with `nrow`
#'         rows.
17
#' @note Internal function do not use.
18 19 20 21 22 23 24 25 26 27 28
#'
#' @author Eric Coissac <eric.coissac@metabarcoding.org>
#' @author Christelle Gonindard-Melodelima <christelle.gonindard@metabarcoding.org>
#' @rdname internal.rep_matrix
#'
.rep_matrix <- function(x, nrow) {
  N <- nrow(x)

  if ((nrow %% N != 0L)) {
    stop(sprintf(
      "The size of the longest object (%d) is not a multiple of the size of the shortest (%d)",
29
      nrow, N
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    ),
    domain = NA
    )
  }

  rep <- x
  while (nrow(rep) < nrow)
    rep <- rbind(rep, x)

  return(rep)
}

#' Internal function coercing the data to a matrix.
#'
#' @description Transforme the \code{x} value into a \code{numeric matrix} of
#'              the correct size or into a \code{dist} object.
#'
#' @param x  The data to coerce
#' @param nrows  an interger value specifying the number of row
#'               of the returned matrix
50
#' @param contrasts see the \code{contrasts_arg} argument
51
#'               of the \code{\link[ProcMod]{procmod_frame}}
52
#'               constructor.
53 54
#'
#' @return a new numeric matrix with correct size.
55
#' @note Internal function do not use.
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
#'
#' @author Eric Coissac <eric.coissac@metabarcoding.org>
#' @author Christelle Gonindard-Melodelima <christelle.gonindard@metabarcoding.org>
#' @rdname internal.procmod_coerce_value
#'
.procmod_coerce_value <- function(x, nrows = 0, contrasts = NULL) {
  xi <- if (is.data.frame(x)) {
    as.matrix(x)
  } else if (is.matrix(x) || inherits(x, "dist")) {
    x
  } else if (is.factor(x)) {
    if (is.null(contrasts)) {
      contrasts(x)[x, ]
    } else if (is.character(contrasts) || is.function(contrasts)) {
      match.fun(contrasts, descend = FALSE)(x)[x, ]
    } else {
      contrasts[x, ]
    }
  }
  else {
    as.matrix(x)
  }

  if (!(is.matrix(xi) || inherits(x, "dist"))) {
    stop("Value cannot be coerced to a Matrix")
  }

  if (is.matrix(xi)) {
    dxi <- dim(xi)
    rownamesi <- rownames(xi)
    colnamesi <- colnames(xi)

    xi <- as.numeric(xi)

    dim(xi) <- dxi
    rownames(xi) <- rownamesi
    colnames(xi) <- colnamesi

    N <- nrow(xi)

    if (nrows > 0L && N < nrows) {
      if (N > 0L && (nrows %% N == 0L)) {
        xi <- .rep_matrix(xi, nrow = nrows)
      } else {
        stop(sprintf(
          ngettext(
            N, "replacement has %d row, data has %d",
            "replacement has %d rows, data has %d"
          ),
          N, nrows
        ),
        domain = NA
        )
      }
    }
  }
  else {
    N <- attr(xi, "Size")
    if (nrows > 0L && N != nrows) {
      stop(sprintf(
        ngettext(
          N, "replacement has %d row, data has %d",
          "replacement has %d rows, data has %d"
        ),
        N, nrows
      ),
      domain = NA
      )
    }
  }

  return(xi)
}

.siteNames <- function(x) {
  if (inherits(x, "dist")) {
    attr(x, "Labels")
  } else {
    rownames(x)
  }
}

`.siteNames<-` <- function(x, value) {
  if (inherits(x, "dist")) {
    stopifnot(is.null(value) || length(value) == attr(x, "Size"))
    attr(x, "Labels") <- value
  }
  else {
    rownames(x) <- value
  }

  x
}


.siteCount <- function(x) {
  if (inherits(x, "dist")) {
    attr(x, "Size")
  } else {
    nrow(x)
  }
}


.siteSelect <- function(x, select) {
  if (inherits(x, "dist")) {
    as.dist(as.matrix(x)[select, select, drop = FALSE])
  } else {
    x[select, , drop = FALSE]
  }
}


169
#' The procmod_frame data structure.
170
#'
171 172
#' A \code{procmod_frame} can be considered as the analog of a
#' \code{data.frame} for vector data. In a \code{procmod_frame}
173 174 175 176 177
#' each element, equivalent to a column in a \code{data.frame}
#' is a numeric matrix or a distance matrix object (\code{dist}).
#' Every element must describe the same number of individuals.
#' Therefore every numeric matrix must have the same number of row
#' (\code{nrow}) and every distance matrix must have the same size
178
#' (\code{attr(d,"Size")}). A \code{procmod_frame} can simultaneously
179 180
#' contain both types of data, numeric and distance matrix.
#'
181
#' @param ... a set of objects to aggregate into a
182
#'        \code{procmod_frame}. These objects can be
183 184 185
#'        numeric matrices, or dist objects. Every objects
#'        must have the same number of row.
#'
186
#' @param row_names a character vector containing names associated
187 188
#'        to each row.
#'
189
#' @param check_rows a logical value. When set to \code{TRUE}, its
190
#'        default value, the number of row of every elements of the
191
#'        \code{procmod_frame} are tested for equality. Otherwise no
192 193
#'        check is done.
#'
194
#' @param reorder_rows a logical value. When set to \code{TRUE}, its
195
#'        default value, every elements of the
196
#'        \code{procmod_frame} are reordered according to the \code{row_names}
197 198
#'        order. Otherwise nothing is done.
#'
199
#' @param contrasts_arg	A list, whose entries are values
200 201 202 203 204
#'        (numeric matrices or character strings naming functions)
#'        to be used as replacement values for the contrasts
#'        replacement function and whose names are the names
#'        of columns of data containing factors.
#'
205
#' @return a \code{procmod_frame} instance.
206 207 208 209 210 211 212
#'
#' @examples
#' library(vegan)
#' data(bacteria)
#' data(eukaryotes)
#' data(soil)
#'
213
#' dataset <- procmod_frame(euk = vegdist(decostand(eukaryotes,
214 215 216 217 218 219 220 221 222 223 224 225 226
#'                                                  method = "hellinger"),
#'                                        method = "euclidean"),
#'                          bac = vegdist(decostand(bacteria,
#'                                                  method = "hellinger"),
#'                                        method = "euclidean"),
#'                          soil = scale(soil,
#'                                       center = TRUE,
#'                                       scale  = TRUE))
#' length(dataset)
#' nrow(dataset)
#' ncol(dataset)
#' dataset$euk
#'
227 228 229
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
230
procmod_frame <- function(...,
231 232 233 234 235
                          row_names = NULL,
                          check_rows = TRUE,
                          reorder_rows = TRUE,
                          contrasts_arg = NULL) {
  has.row_names <- !missing(row_names)
236

237
  varnames <- dots_names(...)
238 239 240 241 242 243

  x <- list(...)
  n <- length(x)

  #  message(x)
  #  message(n)
244
  #  message(row_names)
245

246 247
  if ((!has.row_names || is.null(row_names)) && n >= 1) {
    row_names <- .siteNames(x[[1]])
248 249 250 251 252 253 254
  }

  nrows <- integer(n)
  value <- vector(mode = "list", length = n)

  names(value) <- varnames

255
  # types <- character(n)
256 257

  for (i in seq_len(n)) {
258
    contrasts <- contrasts_arg[varnames[i]]
259 260 261 262 263 264 265 266 267 268 269
    if (i == 1) {
      xi <- .procmod_coerce_value(x[[i]],
        contrasts = contrasts
      )
    } else {
      xi <- .procmod_coerce_value(x[[i]],
        nrows = nrows[1],
        contrasts = contrasts
      )
    }

270 271
    if (reorder_rows &&
      !is.null(row_names) &&
272
      !is.null(.siteNames(xi))) {
273
      xi <- .siteSelect(xi, row_names)
274 275 276 277 278 279 280
    }

    nrows[i] <- .siteCount(xi)
    value[[i]] <- xi
  }

  stopifnot(all(nrows[i] == nrows))
281 282 283 284
  # message(row_names," : ",length(row_names),",",nrows[i])
  if (length(row_names) == nrows[i]) {
    attr(value, "row_names") <- row_names
    if (check_rows) {
285
      for (i in seq_len(n)) {
286
        if (!all(row_names == .siteNames(value[[i]]))) {
287 288 289 290 291
          stop("Row names among matrices are not consistant")
        }
      }
    } else {
      for (i in seq_len(n))
292
        .siteNames(value[[i]]) <- row_names
293 294 295 296 297 298 299
    }
  }
  else {
    for (i in seq_len(n))
      .siteNames(value[[i]]) <- NULL
  }

300
  make_subS3Class(value, "procmod_frame")
301 302 303 304 305
}

#'
#' Check if an object is a ProcMod Frame.
#'
306 307 308
#' @param x a R \code{object to test}
#'
#' @return a \code{logical} value equals to
309
#'         \code{TRUE} if \code{x} is a \code{procmod_frame},
310 311
#'         \code{FALSE} otherwise.
#'
312 313 314 315 316 317 318 319 320 321 322 323
#' @examples
#' # Builds a procmod_frame with two random matrices
#' m1 <- simulate_matrix(10,20)
#' m2 <- simulate_matrix(10,30)
#' pmf <- procmod_frame(m1 = m1, m2 = m2)
#'
#' # Returns TRUE
#' is_procmod_frame(pmf)
#'
#' # Returns FALSE
#' is_procmod_frame(3)
#'
324 325
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
326
#' @export
327
is_procmod_frame <- function(x) {
328
  inherits(x, "procmod_frame")
329 330 331 332 333
}

#'
#' Coerce to a ProcMod Frame.
#'
334 335 336 337 338 339
#' Conversion methods are proposed for \code{list},
#' \code{matrix} and \code{array}.
#'
#' @param data a R object to coerce.
#' @param ... supplementary parameters used in some
#'            implementation of that method
340
#' @return a \code{procmod_frame} object
341
#'
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
#' @examples
#' # Builds a list containing two random matrices
#' m1 <- simulate_matrix(10,20)
#' m2 <- simulate_matrix(10,30)
#' l <- list(m1 = m1, m2 = m2)
#'
#' # Converts the list to a procmod_frame
#' pmf1 <- as_procmod_frame(l)
#'
#' # Builds a procmod_frame from a matrix
#' m3 <- matrix(1:12,nrow=3)
#' pmf2 <- as_procmod_frame(matrix(1:12,nrow=3))
#' # Returns 4, the column count of the input matrix
#' length(pmf2)
#'
#' # Builds a 3D array
#' a <- array(1:24,dim = c(3,4,2))
#'
#' # The conversion to a procmod_frame makes
#' # an procmod element from each third dimension
#' as_procmod_frame(a)
#'
364 365
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
366
#' @export
367 368
as_procmod_frame <- function(data, ...) {
  UseMethod("as_procmod_frame", data)
369 370
}

371
#' @rdname as_procmod_frame
372
#' @export
373
as_procmod_frame.list <- function(data, ...) {
374
  data <- c(data, list(...))
375
  do.call(procmod_frame, data)
376 377
}

378
#' @rdname as_procmod_frame
379
#' @export
380
as_procmod_frame.procmod_frame <- function(data, ...) {
381 382 383
  data
}

384
#' @rdname as_procmod_frame
385
#' @export
386
as_procmod_frame.array <- function(data, ...) {
387 388 389 390 391 392 393 394 395 396 397 398 399 400
  di <- dim(data)
  stopifnot(length(di) == 3)

  l <- lapply(
    seq_len(di[3]),
    function(i) data[, , i]
  )

  if (length(attr(data, "dimnames")) == 3) {
    names(l) <- attr(data, "dimnames")[[3]]
  }

  data <- c(l, list(...))

401
  do.call(procmod_frame, l)
402 403
}

404
# #' @rdname procmod_frame
405
# #' @export
406
# as_procmod_frame.pm <- function(data, ...) {
407 408
#   vars.procmod(terms(data), data$model)
# }
409

410
#' @rdname as_procmod_frame
411
#' @export
412
as_procmod_frame.matrix <- function(data, ...) {
413 414 415 416 417 418 419 420 421
  l <- vector(mode = "list", length = ncol(data))
  for (i in seq_len(ncol(data))) {
    l[[i]] <- data[, i]
  }

  if (!is.null(colnames(data))) {
    names(l) <- colnames(data)
  }

422
  as_procmod_frame(l)
423 424
}

425 426
#' Dimensions of a ProcMod Frame.
#'
427 428 429 430
#' Dimension 1 is the number of rows (individus)
#' shared by the aggregated matrices. Dimension 2
#' is the number of aggregated matrices
#'
431
#' @param x a \code{\link[ProcMod]{procmod_frame}}
432
#'          object
433
#'
434 435 436 437 438 439 440
#' @examples
#' # Builds a procmod_frame with two random matrices
#' m1 <- simulate_matrix(10,20)
#' m2 <- simulate_matrix(10,30)
#' pmf <- procmod_frame(m1 = m1, m2 = m2)
#' dim(pmf)
#'
441 442 443
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
444
dim.procmod_frame <- function(x)
445 446 447 448 449
  return(c(.siteCount(x[[1]]), length(x)))

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
450
`[[<-.procmod_frame` <- function(x, i, value) {
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
  cl <- class(x)
  nrows <- .siteCount(x)
  class(x) <- "list"

  if (!is.null(value)) {
    value <- .procmod_coerce_value(value, nrows)
    N <- .siteCount(value)

    if (N > nrows) {
      stop(sprintf(
        ngettext(
          N, "replacement has %d row, data has %d",
          "replacement has %d rows, data has %d"
        ),
        N, nrows
      ),
      domain = NA
      )
    }

    if (N < nrows) {
      stop(sprintf(
        ngettext(
          N, "replacement has %d row, data has %d",
          "replacement has %d rows, data has %d"
        ),
        N, nrows
      ),
      domain = NA
      )
    }
  }

484
  .siteNames(value) <- attr(x, "row_names")
485 486 487 488 489 490 491 492 493 494

  x[[i]] <- value
  class(x) <- cl

  return(x)
}

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
495
`$<-.procmod_frame` <- function(x, name, value) {
496
  x[[name]] <- value
497 498

  x
499 500 501 502 503
}

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
504
`[.procmod_frame` <- function(x, i, j,
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
                              drop = TRUE) {
  has.j <- !missing(j)
  has.i <- !missing(i)
  has.drop <- !missing(drop)
  Narg <- nargs() - 2 + (has.i | has.j | has.drop) - has.drop

  # message("Nargs = ",Narg," i:",has.i," j:",has.j," drop:",has.drop)

  if (!all(names(sys.call()) %in% c("", "drop"))) {
    warning("named arguments other than 'drop' are discouraged")
  }


  if (!has.i && !has.j) {
    # Case 1 : X[]
    return(x)
  } else if (!has.i && has.j) {
    # Case 2 : X[,j] ou x[i]
    # message('Case 2 : X[,j]')
    y <- as.list(x)[j]
  }
  else if (has.i && Narg == 1) {
    # Case 3 : X[,j] ou x[i]
    # message('Case 3 : X[i]')
    y <- as.list(x)[i]
  }
  else if (has.i && !has.j && Narg > 1) {
    # Case 4 : X[i,]
    # message('Case 4 : X[i,]')
    y <- lapply(x, function(m) .siteSelect(m, i))
  }
  else if (has.i && has.j) {
    # message('Case 5 : X[i,j]')
    y <- x[j, drop = FALSE]
    y <- y[i, , drop = FALSE]
  }

  if (drop && length(y) == 1L) {
    y <- y[[1]]
  } else {
545
    y <- make_subS3Class(y, "procmod_frame")
546
    attr(y, "row_names") <- rownames(y[[1]])
547 548
  }

549
  y
550 551
}

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
#' Subsetting Procmod Frames
#'
#' This is the implementation of the \code{\link[base]{subset}} generic function for
#' \code{procmod_frame}.
#'
#' The subset argument works on rows. Note that subset will be evaluated in the
#' \code{procmod_frame}, so columns can be referred to (by name) as variables
#' in the expression (see the examples).
#'
#' The select argument if provided indicates with matrices
#' have to be conserved.  It works by first replacing column names in the selection
#' expression with the corresponding column numbers in the \code{procmod_frame} and then using
#' the resulting integer vector to index the columns. This allows the use of the
#' standard indexing conventions so that for example ranges of columns can
#' be specified easily, or single columns can be dropped (see the examples). Remember
#' that each column of a \code{procmod_frame} is actually a matrix.
#'
#' The drop argument is passed on to the \code{procmod_frame} indexing method.
#' The default value is \code{FALSE}.
#'
#' @param x	object to be subsetted.
#' @param subset	logical expression indicating elements or
#'                rows to keep: missing values are taken as false.
#' @param select	expression, indicating columns to select from a data frame.
#' @param drop	  passed on to [ indexing operator.
#' @param ...	further arguments to be passed to or from other methods.
#'
#' @return A \code{procmod_frame} containing just the selected rows and columns.
#'
#' @examples
#' library(vegan)
#' data(bacteria)
#' data(eukaryotes)
#' data(soil)
#'
#' dataset <- procmod_frame(euk = vegdist(decostand(eukaryotes,
#'                                                  method = "hellinger"),
#'                                        method = "euclidean"),
#'                          bac = vegdist(decostand(bacteria,
#'                                                  method = "hellinger"),
#'                                        method = "euclidean"),
#'                          soil = scale(soil,
#'                                       center = TRUE,
#'                                       scale  = TRUE))
#' dim(dataset)
#'
#' higher_ph = subset(dataset,soil[,"pH"] > 0)
#' dim(higher_ph)
#'
#' without_bacteria = subset(dataset,soil[,"pH"] > 0, -bac)
#' dim(without_bacteria)
#'
604 605 606
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
607
subset.procmod_frame <- function(x, subset, select, drop = FALSE, ...) {
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
  r <- if (missing(subset)) {
    rep_len(TRUE, nrow(x))
  } else {
    e <- substitute(subset)
    r <- eval(e, x, parent.frame())
    if (!is.logical(r)) {
      stop("'subset' must be logical")
    }
    r & !is.na(r)
  }
  vars <- if (missing(select)) {
    TRUE
  } else {
    nl <- as.list(seq_along(x))
    names(nl) <- names(x)
    eval(substitute(select), nl, parent.frame())
  }
  x[r, vars, drop = drop]
}

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
631
as.list.procmod_frame <- function(x, ...) {
632
  class(x) <- "list"
633 634

  x
635
}