Skip to content

Commit

Permalink
Change object class testing to use inherits or is.* instead of class
Browse files Browse the repository at this point in the history
In R 4.X, matrices are now arrays
This means that class(matrix()) will be a two-length vector instead of one-length
if doesn't like two-length vectors, so using class becomes dangerous
Instead, we're using inherits or is.* functions to test object class
  • Loading branch information
mojaveazure committed Dec 4, 2019
1 parent fc92826 commit 288686a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 24 deletions.
6 changes: 3 additions & 3 deletions R/differential_expression.R
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ FindAllMarkers <- function(
return(cond$message)
}
)
if (class(x = genes.de[[i]]) == "character") {
if (is.character(x = genes.de[[i]])) {
messages[[i]] <- genes.de[[i]]
genes.de[[i]] <- NULL
}
Expand Down Expand Up @@ -233,7 +233,7 @@ FindConservedMarkers <- function(
verbose = TRUE,
...
) {
if (class(x = meta.method) != "function") {
if (!is.function(x = meta.method)) {
stop("meta.method should be a function from the metap package. Please see https://cran.r-project.org/web/packages/metap/metap.pdf for a detailed description of the available functions.")
}
object.var <- FetchData(object = object, vars = grouping.var)
Expand Down Expand Up @@ -1412,7 +1412,7 @@ NBModelComparison <- function(y, theta, latent.data, com.fac, grp.fac) {
),
silent = TRUE
)
if (class(x = fit2)[1] == 'numeric' | class(x = fit4)[1] == 'numeric') {
if (is.numeric(x = fit2) || is.numeric(x = fit4)) {
message('One of the glm.nb calls failed')
return(c(rep(x = NA, 5), freqs))
}
Expand Down
8 changes: 4 additions & 4 deletions R/objects.R
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,7 @@ CreateSeuratObject <- function(
warning("Some cells in meta.data not present in provided counts matrix.")
meta.data <- meta.data[intersect(x = rownames(x = meta.data), y = colnames(x = counts)), ]
}
if (class(x = meta.data) == "data.frame") {
if (is.data.frame(x = meta.data)) {
new.meta.data <- data.frame(row.names = colnames(x = counts))
for (ii in 1:ncol(x = meta.data)) {
new.meta.data[rownames(x = meta.data), colnames(x = meta.data)[ii]] <- meta.data[, ii, drop = FALSE]
Expand Down Expand Up @@ -6224,7 +6224,7 @@ setMethod( # because R doesn't allow S3-style [[<- for S4 classes
)
}
# Check keyed objects
if (class(x = value) %in% c('Assay', 'DimReduc')) {
if (inherits(x = value, what = c('Assay', 'DimReduc'))) {
if (length(x = Key(object = value)) == 0) {
Key(object = value) <- paste0(tolower(x = i), '_')
} else if (!grepl(pattern = '^[[:alnum:]]+_$', x = Key(object = value))) {
Expand Down Expand Up @@ -6281,9 +6281,9 @@ setMethod( # because R doesn't allow S3-style [[<- for S4 classes
}
# For Assays, run CalcN
if (inherits(x = value, what = 'Assay')) {
if ((!i %in% Assays(object = x)) |
if ((!i %in% Assays(object = x)) |
(i %in% Assays(object = x) && ! identical(
x = GetAssayData(object = x, assay = i, slot = "counts"),
x = GetAssayData(object = x, assay = i, slot = "counts"),
y = GetAssayData(object = value, slot = "counts"))
)) {
n.calc <- CalcN(object = value)
Expand Down
33 changes: 16 additions & 17 deletions R/preprocessing.R
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ CalculateBarcodeInflections <- function(
}
)$x
## workaround for aggregate behavior noted above
if (class(x = whichmin_list) == 'list') { # uneven lengths
if (is.list(x = whichmin_list)) { # uneven lengths
is_inflection <- unlist(x = whichmin_list)
} else if (class(x = whichmin_list) == 'matrix') { # even lengths
} else if (is.matrix(x = whichmin_list)) { # even lengths
is_inflection <- as.vector(x = t(x = whichmin_list))
}
tmp <- cbind(barcode_dist_sub, is_inflection)
Expand Down Expand Up @@ -191,15 +191,15 @@ CreateGeneActivityMatrix <- function(
peak.df <- as.data.frame(x = peak.df)
colnames(x = peak.df) <- c("chromosome", 'start', 'end')
peaks.gr <- GenomicRanges::makeGRangesFromDataFrame(df = peak.df)

# if any peaks start at 0, change to 1
# otherwise GenomicRanges::distanceToNearest will not work
# otherwise GenomicRanges::distanceToNearest will not work
BiocGenerics::start(peaks.gr[BiocGenerics::start(peaks.gr) == 0, ]) <- 1

# get annotation file, select genes
gtf <- rtracklayer::import(con = annotation.file)
gtf <- GenomeInfoDb::keepSeqlevels(x = gtf, value = seq.levels, pruning.mode = 'coarse')

# change seqlevelsStyle if not the same
if (!any(GenomeInfoDb::seqlevelsStyle(x = gtf) == GenomeInfoDb::seqlevelsStyle(x = peaks.gr))) {
GenomeInfoDb::seqlevelsStyle(gtf) <- GenomeInfoDb::seqlevelsStyle(peaks.gr)
Expand All @@ -216,11 +216,11 @@ CreateGeneActivityMatrix <- function(
keep.overlaps <- gene.distances[rtracklayer::mcols(x = gene.distances)$distance == 0]
peak.ids <- peaks.gr[S4Vectors::queryHits(x = keep.overlaps)]
gene.ids <- gtf.genes[S4Vectors::subjectHits(x = keep.overlaps)]

# Some GTF rows will not have gene_name attribute
# Replace it by gene_id attribute
gene.ids$gene_name[is.na(gene.ids$gene_name)] <- gene.ids$gene_id[is.na(gene.ids$gene_name)]

peak.ids$gene.name <- gene.ids$gene_name
peak.ids <- as.data.frame(x = peak.ids)
peak.ids$peak <- rownames(peak.matrix)[S4Vectors::queryHits(x = keep.overlaps)]
Expand Down Expand Up @@ -582,10 +582,10 @@ GetResidual <- function(
#' mat_norm
#'
LogNormalize <- function(data, scale.factor = 1e4, verbose = TRUE) {
if (class(x = data) == "data.frame") {
if (is.data.frame(x = data)) {
data <- as.matrix(x = data)
}
if (class(x = data) != "dgCMatrix") {
if (!inherits(x = data, what = 'dgCMatrix')) {
data <- as(object = data, Class = "dgCMatrix")
}
# call Rcpp function to normalize
Expand Down Expand Up @@ -1066,10 +1066,10 @@ Read10X_h5 <- function(filename, use.names = TRUE, unique.features = TRUE) {
#' mat_norm
#'
RelativeCounts <- function(data, scale.factor = 1, verbose = TRUE) {
if (class(x = data) == "data.frame") {
if (is.data.frame(x = data)) {
data <- as.matrix(x = data)
}
if (class(x = data) != "dgCMatrix") {
if (!inherits(x = data, what = 'dgCMatrix')) {
data <- as(object = data, Class = "dgCMatrix")
}
if (verbose) {
Expand Down Expand Up @@ -1419,10 +1419,10 @@ SubsetByBarcodeInflections <- function(object) {
#' mat_norm <- TF.IDF(data = mat)
#'
TF.IDF <- function(data, verbose = TRUE) {
if (class(x = data) == "data.frame") {
if (is.data.frame(x = data)) {
data <- as.matrix(x = data)
}
if (class(x = data) != "dgCMatrix") {
if (!inherits(x = data, what = 'dgCMatrix')) {
data <- as(object = data, Class = "dgCMatrix")
}
if (verbose) {
Expand Down Expand Up @@ -2502,7 +2502,6 @@ ClassifyCells <- function(data, q) {
message("No threshold found for ", colnames(x = data)[i], "...")
}
)
# if (class(x = model) == "character") {
if (is.character(x = model)) {
next
}
Expand Down Expand Up @@ -2569,10 +2568,10 @@ ClassifyCells <- function(data, q) {
# @import Matrix
#
CustomNormalize <- function(data, custom_function, margin, verbose = TRUE) {
if (class(x = data) == "data.frame") {
if (is.data.frame(x = data)) {
data <- as.matrix(x = data)
}
if (class(x = data) != "dgCMatrix") {
if (!inherits(x = data, what = 'dgCMatrix')) {
data <- as(object = data, Class = "dgCMatrix")
}
myapply <- ifelse(test = verbose, yes = pbapply, no = apply)
Expand Down Expand Up @@ -2782,7 +2781,7 @@ NBResiduals <- function(fmla, regression.mat, gene, return.mode = FALSE) {
data = regression.mat
),
silent = TRUE)
if (class(fit)[1] == 'numeric') {
if (is.numeric(x = fit)) {
message(sprintf('glm.nb failed for gene %s; falling back to scale(log(y+1))', gene))
resid <- scale(x = log(x = regression.mat[, 'GENE'] + 1))[, 1]
mode <- 'scale'
Expand Down

0 comments on commit 288686a

Please sign in to comment.