procmod_frame.R 12.9 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 186 187 188 189 190
#'        numeric matrices, or dist objects. Every objects
#'        must have the same number of row.
#'
#' @param row.names a character vector containing names associated
#'        to each row.
#'
#' @param check.rows a logical value. When set to \code{TRUE}, its
#'        default value, the number of row of every elements of the
191
#'        \code{procmod_frame} are tested for equality. Otherwise no
192 193 194 195
#'        check is done.
#'
#' @param reorder.rows a logical value. When set to \code{TRUE}, its
#'        default value, every elements of the
196
#'        \code{procmod_frame} are reordered according to the \code{row.names}
197 198 199 200 201 202 203 204
#'        order. Otherwise nothing is done.
#'
#' @param contrasts.arg	A list, whose entries are values
#'        (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
                          row.names = NULL,
232 233
                          check.rows = TRUE,
                          reorder.rows = TRUE,
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                          contrasts.arg = NULL) {
  has.row.names <- !missing(row.names)

  varnames <- dots.names(...)

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

  #  message(x)
  #  message(n)
  #  message(row.names)

  if ((!has.row.names || is.null(row.names)) && n >= 1) {
    row.names <- .siteNames(x[[1]])
  }

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

  names(value) <- varnames

255
  # types <- character(n)
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

  for (i in seq_len(n)) {
    contrasts <- contrasts.arg[varnames[i]]
    if (i == 1) {
      xi <- .procmod_coerce_value(x[[i]],
        contrasts = contrasts
      )
    } else {
      xi <- .procmod_coerce_value(x[[i]],
        nrows = nrows[1],
        contrasts = contrasts
      )
    }

    if (reorder.rows &&
      !is.null(row.names) &&
      !is.null(.siteNames(xi))) {
      xi <- .siteSelect(xi, row.names)
    }

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

  stopifnot(all(nrows[i] == nrows))
  # message(row.names," : ",length(row.names),",",nrows[i])
  if (length(row.names) == nrows[i]) {
    attr(value, "row.names") <- row.names
    if (check.rows) {
      for (i in seq_len(n)) {
        if (!all(row.names == .siteNames(value[[i]]))) {
          stop("Row names among matrices are not consistant")
        }
      }
    } else {
      for (i in seq_len(n))
        .siteNames(value[[i]]) <- row.names
    }
  }
  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 312 313
#'         \code{FALSE} otherwise.
#'
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
314
#' @export
315 316
is.procmod_frame <- function(x) {
  inherits(x, "procmod_frame")
317 318 319 320 321
}

#'
#' Coerce to a ProcMod Frame.
#'
322 323 324 325 326 327
#' 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
328
#' @return a \code{procmod_frame} object
329 330 331
#'
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
332
#' @export
333 334
as.procmod_frame <- function(data, ...) {
  UseMethod("as.procmod_frame", data)
335 336
}

337
#' @rdname as.procmod_frame
338
#' @export
339
as.procmod_frame.list <- function(data, ...) {
340
  data <- c(data, list(...))
341
  do.call(procmod_frame, data)
342 343
}

344
#' @rdname as.procmod_frame
345
#' @export
346
as.procmod_frame.procmod_frame <- function(data, ...) {
347 348 349
  data
}

350
#' @rdname as.procmod_frame
351
#' @export
352
as.procmod_frame.array <- function(data, ...) {
353 354 355 356 357 358 359 360 361 362 363 364 365 366
  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(...))

367
  do.call(procmod_frame, l)
368 369
}

370
# #' @rdname procmod_frame
371
# #' @export
372
# as.procmod_frame.pm <- function(data, ...) {
373 374
#   vars.procmod(terms(data), data$model)
# }
375

376
#' @rdname as.procmod_frame
377
#' @export
378
as.procmod_frame.matrix <- function(data, ...) {
379 380 381 382 383 384 385 386 387
  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)
  }

388
  as.procmod_frame(l)
389 390
}

391 392
#' Dimensions of a ProcMod Frame.
#'
393
#' @param x a \code{\link[ProcMod]{procmod_frame}}
394
#'          object
395 396 397 398
#'
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
399
dim.procmod_frame <- function(x)
400 401 402 403 404
  return(c(.siteCount(x[[1]]), length(x)))

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
405
`[[<-.procmod_frame` <- function(x, i, value) {
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
  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
      )
    }
  }

  .siteNames(value) <- attr(x, "row.names")

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

  return(x)
}

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
450
`$<-.procmod_frame` <- function(x, name, value) {
451
  x[[name]] <- value
452 453

  x
454 455 456 457 458
}

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
459
`[.procmod_frame` <- function(x, i, j,
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
                              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 {
500
    y <- make_subS3Class(y, "procmod_frame")
501 502 503
    attr(y, "row.names") <- rownames(y[[1]])
  }

504
  y
505 506 507 508 509
}

#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
510
subset.procmod_frame <- function(x, subset, select, drop = FALSE, ...) {
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  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
534
as.list.procmod_frame <- function(x, ...) {
535
  class(x) <- "list"
536 537

  x
538
}