diff --git a/R/cell_segmentation.R b/R/cell_segmentation.R index 6c5df37ad..db82d5806 100644 --- a/R/cell_segmentation.R +++ b/R/cell_segmentation.R @@ -51,10 +51,10 @@ doCellSegmentation <- function(raster_img, # sliding window start_x <- 0 end_x <- start_x + tile_dim - for (i in 1:nxwindow) { + for (i in seq_len(nxwindow)) { start_y <- 0 end_y <- start_y + tile_dim - for (j in 1:nywindow) { + for (j in seq_len(nywindow)) { ext_crop <- terra::ext(c(start_x, end_x, start_y, end_y)) img_crop <- terra::crop(raster_img, ext_crop, snap = "in") img_crop_rescaled <- terra::aggregate(img_crop, reduce_resolution) diff --git a/R/clustering.R b/R/clustering.R index 625db7e35..54ff5e838 100644 --- a/R/clustering.R +++ b/R/clustering.R @@ -113,7 +113,7 @@ doLeidenCluster <- function(gobject, if (isTRUE(set_seed)) { seed_number <- as.integer(seed_number) } else { - seed_number <- as.integer(sample(x = 1:10000, size = 1)) + seed_number <- as.integer(sample(x = seq_len(10000), size = 1)) } ## extract NN network @@ -551,7 +551,7 @@ doGiottoClustree <- function(gobject, if (isTRUE(set_seed)) { seed_number <- as.integer(seed_number) } else { - seed_number <- as.integer(sample(x = 1:10000, size = 1)) + seed_number <- as.integer(sample(x = seq_len(10000), size = 1)) } network_edge_dt <- data.table::as.data.table(igraph::as_data_frame( @@ -1102,9 +1102,9 @@ doSNNCluster <- function(gobject, cell_id_numeric <- unique(x = c(igraph_DT$from, igraph_DT$to)) names(cell_id_numeric) <- seq_along(cell_id_numeric) igraph_DT[, from_T := as.numeric(names(cell_id_numeric[ - cell_id_numeric == from])), by = 1:nrow(igraph_DT)] + cell_id_numeric == from])), by = seq_len(nrow(igraph_DT))] igraph_DT[, to_T := as.numeric(names(cell_id_numeric[ - cell_id_numeric == to])), by = 1:nrow(igraph_DT)] + cell_id_numeric == to])), by = seq_len(nrow(igraph_DT))] temp_igraph_DT <- igraph_DT[, .(from_T, to_T, weight, distance)] data.table::setnames( temp_igraph_DT, old = c("from_T", "to_T"), new = c("from", "to")) @@ -1116,7 +1116,7 @@ doSNNCluster <- function(gobject, ) ident_clusters_DT <- data.table::data.table( - "cell_ID" = cell_id_numeric[1:nrow(kNN_object$dist)], + "cell_ID" = cell_id_numeric[seq_len(nrow(kNN_object$dist))], "name" = sNN_clusters$cluster) data.table::setnames(ident_clusters_DT, "name", name) @@ -1247,7 +1247,7 @@ doKmeans <- function(gobject, ) dimensions_to_use <- dimensions_to_use[ - dimensions_to_use %in% 1:ncol(dim_coord[])] + dimensions_to_use %in% seq_len(ncol(dim_coord[]))] matrix_to_use <- dim_coord[][, dimensions_to_use] } else { values <- match.arg( @@ -1470,7 +1470,7 @@ doHclust <- function(gobject, ) dimensions_to_use <- dimensions_to_use[ - dimensions_to_use %in% 1:ncol(dim_coord)] + dimensions_to_use %in% seq_len(ncol(dim_coord))] matrix_to_use <- dim_coord[, dimensions_to_use] } else { ## using original matrix ## @@ -2813,7 +2813,8 @@ getClusterSimilarity <- function(gobject, cor_table[, c("group1", "group2") := list( as.character(group1), as.character(group2))] cor_table[, unified_group := paste( - sort(c(group1, group2)), collapse = "--"), by = 1:nrow(cor_table)] + sort(c(group1, group2)), collapse = "--"), + by = seq_len(nrow(cor_table))] cor_table <- cor_table[!duplicated(cor_table[, .(value, unified_group)])] cor_table <- merge( @@ -2933,7 +2934,7 @@ mergeClusters <- function(gobject, ## get list of correlated groups finallist <- list() start_i <- 1 - for (row in 1:nrow(filter_set)) { + for (row in seq_len(nrow(filter_set))) { first_clus <- filter_set[row][["group1"]] second_clus <- filter_set[row][["group2"]] @@ -2971,7 +2972,7 @@ mergeClusters <- function(gobject, as.character(get(cluster_column)) %in% finalvec, names(finalvec[finalvec == as.character(get(cluster_column))]), as.character(get(cluster_column)) - ), by = 1:nrow(metadata)] + ), by = seq_len(nrow(metadata))] @@ -3205,7 +3206,7 @@ getDendrogramSplits <- function(gobject, splitDT <- data.table::as.data.table(t_flex( data.table::as.data.table(splitList[[2]]))) colnames(splitDT) <- c("node_h", "tree_1", "tree_2") - splitDT[, nodeID := paste0("node_", 1:.N)] + splitDT[, nodeID := paste0("node_", seq_len(.N))] return(splitDT) } @@ -3317,7 +3318,7 @@ doClusterProjection <- function(target_gobject, dim_coord <- dim_obj[] dimensions_to_use <- dimensions_to_use[ - dimensions_to_use %in% 1:ncol(dim_coord)] + dimensions_to_use %in% seq_len(ncol(dim_coord))] matrix_to_use <- dim_coord[, dimensions_to_use] ## create the training and testset from the matrix diff --git a/R/cross_section.R b/R/cross_section.R index f1fac6960..86fa916c4 100644 --- a/R/cross_section.R +++ b/R/cross_section.R @@ -520,7 +520,7 @@ createCrossSection <- function(gobject, spatial_locations <- as.matrix(spatial_locations) rownames(spatial_locations) <- cell_IDs - cell_ID_vec <- c(1:nrow(spatial_locations)) + cell_ID_vec <- seq_len(nrow(spatial_locations)) names(cell_ID_vec) <- rownames(spatial_locations) # generate section plane equation @@ -542,7 +542,7 @@ createCrossSection <- function(gobject, message("either point or norm vector was not provided.") } else { plane_equation <- c() - plane_equation[1:3] <- normVector + plane_equation[seq_len(3)] <- normVector plane_equation[4] <- -point1 %*% normVector } } else if (method == "point and two plane vectors") { @@ -551,7 +551,7 @@ createCrossSection <- function(gobject, provided.") } else { normVector <- crossprod(planeVector1, planeVector2) - plane_equation[1:3] <- normVector + plane_equation[seq_len(3)] <- normVector plane_equation[4] <- -point1 %*% normVector } } else if (method == "3 points") { @@ -561,7 +561,7 @@ createCrossSection <- function(gobject, planeVector1 <- point2 - point1 planeVector2 <- point3 - point1 normVector <- crossprod(planeVector1, planeVector2) - plane_equation[1:3] <- normVector + plane_equation[seq_len(3)] <- normVector plane_equation[4] <- -point1 %*% normVector } } @@ -584,7 +584,7 @@ createCrossSection <- function(gobject, spatial_locations, as.matrix(rep(1, dim(spatial_locations)[1]))) norm_vec <- function(x) sqrt(sum(x^2)) distance_to_plane_vector <- abs(spatial_locations_mat %*% as.matrix( - plane_equation) / norm_vec(plane_equation[1:3])) + plane_equation) / norm_vec(plane_equation[seq_len(3)])) # select cells within section ### cell_subset <- distance_to_plane_vector <= max_distance_to_section_plane @@ -604,7 +604,7 @@ createCrossSection <- function(gobject, cell_subset_projection_locations <- t(apply( cell_subset_spatial_locations, 1, function(x) projection_fun(x, plane_point = plane_point, - plane_norm = plane_equation[1:3]))) + plane_norm = plane_equation[seq_len(3)]))) # get the local coordinates of selected cells on the section plane cell_subset_projection_PCA <- stats::prcomp( diff --git a/R/differential_expression.R b/R/differential_expression.R index e476e2e62..644f28c58 100644 --- a/R/differential_expression.R +++ b/R/differential_expression.R @@ -577,7 +577,7 @@ findGiniMarkers <- function(gobject, aggr_sc[, comb_score := (expression_gini * expression_rank) * ( detection_gini * detection_rank)] setorder(aggr_sc, cluster, -comb_score) - aggr_sc[, comb_rank := 1:.N, by = cluster] + aggr_sc[, comb_rank := seq_len(.N), by = cluster] top_feats_scores <- aggr_sc[comb_rank <= min_feats | ( expression_rank <= rank_score & detection_rank <= rank_score)] diff --git a/R/dimension_reduction.R b/R/dimension_reduction.R index e384b7f1b..249c677d8 100644 --- a/R/dimension_reduction.R +++ b/R/dimension_reduction.R @@ -60,13 +60,13 @@ # PC loading loadings <- pca_res$ind$coord rownames(loadings) <- rownames(x) - colnames(loadings) <- paste0("Dim.", 1:ncol(loadings)) + colnames(loadings) <- paste0("Dim.", seq_len(ncol(loadings))) # coordinates coords <- sweep(pca_res$var$coord, - 2, sqrt(eigenvalues[1:ncp]), FUN = "/") + 2, sqrt(eigenvalues[seq_len(ncp)]), FUN = "/") rownames(coords) <- colnames(x) - colnames(coords) <- paste0("Dim.", 1:ncol(coords)) + colnames(coords) <- paste0("Dim.", seq_len(ncol(coords))) result <- list( eigenvalues = eigenvalues, loadings = loadings, coords = coords) @@ -94,14 +94,14 @@ # PC loading loadings <- sweep( - pca_res$var$coord, 2, sqrt(eigenvalues[1:ncp]), FUN = "/") + pca_res$var$coord, 2, sqrt(eigenvalues[seq_len(ncp)]), FUN = "/") rownames(loadings) <- colnames(x) - colnames(loadings) <- paste0("Dim.", 1:ncol(loadings)) + colnames(loadings) <- paste0("Dim.", seq_len(ncol(loadings))) # coordinates coords <- pca_res$ind$coord rownames(coords) <- rownames(x) - colnames(coords) <- paste0("Dim.", 1:ncol(coords)) + colnames(coords) <- paste0("Dim.", seq_len(ncol(coords))) result <- list( eigenvalues = eigenvalues, loadings = loadings, coords = coords) @@ -189,11 +189,11 @@ # PC loading loadings <- pca_res$x rownames(loadings) <- rownames(x) - colnames(loadings) <- paste0("Dim.", 1:ncol(loadings)) + colnames(loadings) <- paste0("Dim.", seq_len(ncol(loadings))) # coordinates coords <- pca_res$rotation rownames(coords) <- colnames(x) - colnames(coords) <- paste0("Dim.", 1:ncol(coords)) + colnames(coords) <- paste0("Dim.", seq_len(ncol(coords))) result <- list( eigenvalues = eigenvalues, loadings = loadings, coords = coords) } else { @@ -228,11 +228,11 @@ # PC loading loadings <- pca_res$rotation rownames(loadings) <- colnames(x) - colnames(loadings) <- paste0("Dim.", 1:ncol(loadings)) + colnames(loadings) <- paste0("Dim.", seq_len(ncol(loadings))) # coordinates coords <- pca_res$x rownames(coords) <- rownames(x) - colnames(coords) <- paste0("Dim.", 1:ncol(coords)) + colnames(coords) <- paste0("Dim.", seq_len(ncol(coords))) result <- list( eigenvalues = eigenvalues, loadings = loadings, coords = coords) } @@ -607,7 +607,7 @@ runPCA <- function(gobject, cell_ID_order <- rownames(x) # create random selection - random_selection <- sort(sample(1:nrow(x), random_subset)) + random_selection <- sort(sample(seq_len(nrow(x)), random_subset)) subsample_matrix <- x[random_selection, ] @@ -647,12 +647,12 @@ runPCA <- function(gobject, # PC loading loadings <- coords rownames(loadings) <- rownames(x) - colnames(loadings) <- paste0("Dim.", 1:ncol(loadings)) + colnames(loadings) <- paste0("Dim.", seq_len(ncol(loadings))) # coordinates coords <- pca_res$rotation rownames(coords) <- colnames(x) - colnames(coords) <- paste0("Dim.", 1:ncol(coords)) + colnames(coords) <- paste0("Dim.", seq_len(ncol(coords))) result <- list( eigenvalues = eigenvalues, loadings = loadings, coords = coords) @@ -661,7 +661,7 @@ runPCA <- function(gobject, cell_ID_order <- rownames(x) # create random selection - random_selection <- sort(sample(1:nrow(x), random_subset)) + random_selection <- sort(sample(seq_len(nrow(x)), random_subset)) subsample_matrix <- x[random_selection, ] if (verbose) message("pca random subset: start") @@ -699,10 +699,10 @@ runPCA <- function(gobject, # PC loading loadings <- pca_res$rotation rownames(loadings) <- colnames(x) - colnames(loadings) <- paste0("Dim.", 1:ncol(loadings)) + colnames(loadings) <- paste0("Dim.", seq_len(ncol(loadings))) # coordinates - colnames(coords) <- paste0("Dim.", 1:ncol(coords)) + colnames(coords) <- paste0("Dim.", seq_len(ncol(coords))) result <- list( eigenvalues = eigenvalues, loadings = loadings, coords = coords) @@ -1094,7 +1094,7 @@ runPCAprojectionBatch <- function(gobject, if (reduction == "cells") { pca_batch_results <- list() - for (batch in 1:batch_number) { + for (batch in seq_len(batch_number)) { if (verbose) wrap_msg("start batch ", batch) if (isTRUE(set_seed)) { @@ -1124,10 +1124,10 @@ runPCAprojectionBatch <- function(gobject, if (batch == 1) { pca_batch_results[[batch]] <- pca_object } else { - for (dimension in 1:ncol(pca_object[["coords"]])) { + for (dimension in seq_len(ncol(pca_object[["coords"]]))) { sum_evaluation <- sum(sign(pca_batch_results[[1]][[ - "coords"]][1:20, dimension]) * - sign(pca_object[["coords"]][1:20, dimension])) + "coords"]][seq_len(20), dimension]) * + sign(pca_object[["coords"]][seq_len(20), dimension])) if (sum_evaluation < 0) { pca_object$coords[, dimension] <- -1 * pca_object$coords[, dimension] pca_object$loadings[, dimension] <- -1 * pca_object$loadings[, dimension] @@ -1155,7 +1155,7 @@ runPCAprojectionBatch <- function(gobject, coords_array <- array( data = coords_vector, dim = c(ncol(expr_values), ncp, length(pca_batch_results))) - coords_all <- apply(coords_array, MARGIN = c(1:2), function(arr) { + coords_all <- apply(coords_array, MARGIN = seq_len(2), function(arr) { mean(arr, na.rm = TRUE) }) rownames(coords_all) <- rownames(pca_batch_results[[1]][["coords"]]) @@ -1167,7 +1167,8 @@ runPCAprojectionBatch <- function(gobject, loadings_array <- array( data = loadings_vector, dim = c(nrow(expr_values), ncp, length(pca_batch_results))) - loadings_all <- apply(loadings_array, MARGIN = c(1:2), function(arr) { + loadings_all <- apply( + loadings_array, MARGIN = seq_len(2), function(arr) { mean(arr, na.rm = TRUE) }) rownames(loadings_all) <- rownames(pca_batch_results[[1]][["loadings"]]) @@ -1180,7 +1181,7 @@ runPCAprojectionBatch <- function(gobject, } else { pca_batch_results <- list() - for (batch in 1:batch_number) { + for (batch in seq_len(batch_number)) { if (verbose) wrap_msg("start batch ", batch) if (isTRUE(set_seed)) { @@ -1211,10 +1212,10 @@ runPCAprojectionBatch <- function(gobject, if (batch == 1) { pca_batch_results[[batch]] <- pca_object } else { - for (dimension in 1:ncol(pca_object[["coords"]])) { + for (dimension in seq_len(ncol(pca_object[["coords"]]))) { sum_evaluation <- sum(sign(pca_batch_results[[1]][[ - "coords"]][1:20, dimension]) * - sign(pca_object[["coords"]][1:20, dimension])) + "coords"]][seq_len(20), dimension]) * + sign(pca_object[["coords"]][seq_len(20), dimension])) if (sum_evaluation < 0) { pca_object$coords[, dimension] <- -1 * pca_object$coords[, dimension] pca_object$loadings[, dimension] <- -1 * pca_object$loadings[, dimension] @@ -1242,7 +1243,7 @@ runPCAprojectionBatch <- function(gobject, coords_array <- array( data = coords_vector, dim = c(ncol(expr_values), ncp, length(pca_batch_results))) - coords_all <- apply(coords_array, MARGIN = c(1:2), function(arr) { + coords_all <- apply(coords_array, MARGIN = seq_len(2), function(arr) { mean(arr, na.rm = TRUE) }) rownames(coords_all) <- rownames(pca_batch_results[[1]][["coords"]]) @@ -1254,7 +1255,8 @@ runPCAprojectionBatch <- function(gobject, loadings_array <- array( data = loadings_vector, dim = c(nrow(expr_values), ncp, length(pca_batch_results))) - loadings_all <- apply(loadings_array, MARGIN = c(1:2), function(arr) { + loadings_all <- apply( + loadings_array, MARGIN = seq_len(2), function(arr) { mean(arr, na.rm = TRUE) }) rownames(loadings_all) <- rownames(pca_batch_results[[1]][["loadings"]]) @@ -1548,7 +1550,7 @@ create_screeplot <- function(eigs, ncp = 20, ylim = c(0, 20)) { pl <- ggplot2::ggplot() pl <- pl + ggplot2::theme_bw() pl <- pl + ggplot2::geom_bar( - data = screeDT[1:ncp], + data = screeDT[seq_len(ncp)], ggplot2::aes(x = PC, y = var_expl), stat = "identity") pl <- pl + ggplot2::coord_cartesian(ylim = ylim) pl <- pl + ggplot2::theme( @@ -1558,7 +1560,7 @@ create_screeplot <- function(eigs, ncp = 20, ylim = c(0, 20)) { cpl <- ggplot2::ggplot() cpl <- cpl + ggplot2::theme_bw() cpl <- cpl + ggplot2::geom_bar( - data = screeDT[1:ncp], + data = screeDT[seq_len(ncp)], ggplot2::aes(x = PC, y = var_expl_cum), stat = "identity") cpl <- cpl + ggplot2::theme(axis.text.x = ggplot2::element_text( angle = 45, hjust = 1, vjust = 1)) @@ -1744,7 +1746,7 @@ create_jackstrawplot <- function(jackstraw_data, pl <- ggplot2::ggplot() pl <- pl + ggplot2::theme_bw() pl <- pl + ggplot2::geom_point( - data = testDT[1:ncp], + data = testDT[seq_len(ncp)], ggplot2::aes(x = PC, y = p.val, fill = sign), shape = 21) pl <- pl + ggplot2::scale_fill_manual( values = c("n.s." = "lightgrey", "sign" = "darkorange")) @@ -2397,7 +2399,8 @@ runUMAPprojection <- function(gobject, cell_ID_order <- rownames(matrix_to_use) # create random selection - random_selection <- sort(sample(1:nrow(matrix_to_use), random_subset)) + random_selection <- sort(sample( + seq_len(nrow(matrix_to_use)), random_subset)) subsample_matrix <- matrix_to_use[random_selection, ] uwot_clus_subset <- uwot::umap( @@ -2889,7 +2892,7 @@ runGiottoHarmony <- function(gobject, ) - colnames(harmony_results) <- paste0("Dim.", 1:ncol(harmony_results)) + colnames(harmony_results) <- paste0("Dim.", seq_len(ncol(harmony_results))) rownames(harmony_results) <- rownames(matrix_to_use) harmdimObject <- create_dim_obj( diff --git a/R/general_help.R b/R/general_help.R index 279a963e4..e34c94a65 100644 --- a/R/general_help.R +++ b/R/general_help.R @@ -137,7 +137,7 @@ extended_gini_fun <- function(x, length_x <- length(x) vector_x <- sort(x) - first_set <- vector_x[1:extreme_nr] + first_set <- vector_x[seq_len(extreme_nr)] last_set <- vector_x[(length_x - (extreme_nr - 1)):length_x] random_set <- sample( vector_x[(extreme_nr + 1):(length_x - extreme_nr)], size = sample_nr) @@ -309,7 +309,8 @@ convertEnsemblToGeneSymbol <- function(matrix, mgi_symbol == "", ensembl_gene_id, gene_symbol)] gene_names_DT[, gene_symbol := ifelse( gene_symbol == "temporary", - paste0(mgi_symbol, "--", 1:.N), gene_symbol), by = mgi_symbol] + paste0(mgi_symbol, "--", seq_len(.N)), gene_symbol), + by = mgi_symbol] # filter matrix <- matrix[rownames(matrix) %in% gene_names_DT$ensembl_gene_id, ] @@ -348,7 +349,8 @@ convertEnsemblToGeneSymbol <- function(matrix, hgnc_symbol == "", ensembl_gene_id, gene_symbol)] gene_names_DT[, gene_symbol := ifelse( gene_symbol == "temporary", - paste0(hgnc_symbol, "--", 1:.N), gene_symbol), by = hgnc_symbol] + paste0(hgnc_symbol, "--", seq_len(.N)), gene_symbol), + by = hgnc_symbol] # filter matrix <- matrix[rownames(matrix) %in% gene_names_DT$ensembl_gene_id, ] @@ -464,7 +466,7 @@ get10Xmatrix <- function(path_to_data, barcodesDT <- data.table::fread( input = paste0(path_to_data, "/", barcodes_file), header = FALSE) barcodes_vec <- barcodesDT$V1 - names(barcodes_vec) <- 1:nrow(barcodesDT) + names(barcodes_vec) <- seq_len(nrow(barcodesDT)) # get features and create vector features_file <- grep(files_10X, pattern = "features|genes", value = TRUE) @@ -477,10 +479,10 @@ get10Xmatrix <- function(path_to_data, featuresDT[, total := .N, by = get(g_name)] featuresDT[, gene_symbol := ifelse( - total > 1, paste0(get(g_name), "--", 1:.N), + total > 1, paste0(get(g_name), "--", seq_len(.N)), get(g_name)), by = get(g_name)] features_vec <- featuresDT$gene_symbol - names(features_vec) <- 1:nrow(featuresDT) + names(features_vec) <- seq_len(nrow(featuresDT)) # get matrix matrix_file <- grep(files_10X, pattern = "matrix", value = TRUE) @@ -593,7 +595,7 @@ get10Xmatrix_h5 <- function(path_to_data, # data.table variables nr_name <- name <- uniq_name <- NULL - features_dt[, nr_name := 1:.N, by = name] + features_dt[, nr_name := seq_len(.N), by = name] features_dt[, uniq_name := ifelse( nr_name == 1, name, paste0(name, "_", (nr_name - 1)))] diff --git a/R/giotto_viewer.R b/R/giotto_viewer.R index 2517e5084..ae903aac4 100644 --- a/R/giotto_viewer.R +++ b/R/giotto_viewer.R @@ -85,7 +85,8 @@ write_giotto_viewer_dim_reduction <- function(dim_reduction_cell, dim_red_rounding = NULL, dim_red_rescale = c(-20, 20), output_directory = getwd()) { - dim_red_coord <- dim_reduction_cell[[dim_red]][[dim_red_name]]$coordinates[, 1:2] + dim_red_coord <- dim_reduction_cell[[dim_red]][[ + dim_red_name]]$coordinates[, seq_len(2)] if (is.null(dim_red_coord)) { cat("\n combination of ", dim_red, " and ", dim_red_name, " does not exist \n") @@ -356,7 +357,7 @@ exportGiottoViewer <- function(gobject, expr_values <- as.matrix(expr_values) # swap cell_IDs for numerical values - colnames(expr_values) <- 1:ncol(expr_values) + colnames(expr_values) <- seq_len(ncol(expr_values)) # round values if (!is.null(expression_rounding)) { expr_values <- round(x = expr_values, digits = expression_rounding) diff --git a/R/interactivity.R b/R/interactivity.R index 4446a0704..2fb69e3f1 100644 --- a/R/interactivity.R +++ b/R/interactivity.R @@ -191,7 +191,7 @@ getCellsFromPolygon <- function(gobject, ) ## convert cell spatial locations to spatVector - cells_spatVector <- terra::vect(as.matrix(spatial_locs[, 1:2]), + cells_spatVector <- terra::vect(as.matrix(spatial_locs[, seq_len(2)]), type = "points", atts = spatial_locs ) diff --git a/R/poly_influence.R b/R/poly_influence.R index 18fefd9b8..a0bffa8bb 100644 --- a/R/poly_influence.R +++ b/R/poly_influence.R @@ -179,12 +179,12 @@ showPolygonSizeInfluence <- function(gobject = NULL, k_clusters <- sort(unique(cell_meta[[clus_name]])) num_clusters <- k_clusters[length(k_clusters)] - k_match_clusters <- 1:num_clusters + k_match_clusters <- seq_len(num_clusters) switch_strs <- c() - for (i in 1:num_clusters) { + for (i in seq_len(num_clusters)) { thresh <- 0 clus_match <- NULL - for (j in 1:num_clusters) { + for (j in seq_len(num_clusters)) { c_df <- cell_meta[cell_meta[[clus_name]] == i]$cell_ID nc_df <- cell_meta_new[cell_meta_new[[clus_name]] == j]$cell_ID @@ -198,7 +198,7 @@ showPolygonSizeInfluence <- function(gobject = NULL, k_match_clusters[i] <- clus_match } - for (idx in 1:num_clusters) { + for (idx in seq_len(num_clusters)) { p1 <- k_clusters[[idx]] p2 <- k_match_clusters[[idx]] switch_strs <- c(switch_strs, paste0(p1, "-", p2)) @@ -436,7 +436,7 @@ showCellProportionSwitchedSanKey <- function(gobject = NULL, idx1 <- 1 idx2 <- 1 - for (i in 1:flen) { + for (i in seq_len(flen)) { c_k1[i] <- k1[idx1] - 1 # java zero-index c_k2[i] <- k2[idx2] - 1 # java zero-index @@ -447,7 +447,7 @@ showCellProportionSwitchedSanKey <- function(gobject = NULL, num_occ <- c() - for (i in 1:flen) { + for (i in seq_len(flen)) { num_occ[i] <- dim(na.omit(merged_cmeta[kmeans == (c_k1[i] + 1)][ merged_cmeta[kmeans_small == (c_k2[i] + 1)]]))[[1]] } diff --git a/R/python_hmrf.R b/R/python_hmrf.R index 49f09175b..981e70fb5 100644 --- a/R/python_hmrf.R +++ b/R/python_hmrf.R @@ -1425,7 +1425,8 @@ initHMRF_V2 <- if (use_pca == TRUE) { expr_values <- expr_values[spatial_genes, ] pc.expr <- prcomp(expr_values)[[2]] - use_pca_dim <- use_pca_dim[use_pca_dim %in% 1:ncol(pc.expr)] + use_pca_dim <- use_pca_dim[ + use_pca_dim %in% seq_len(ncol(pc.expr))] y0 <- (pc.expr[, use_pca_dim]) } else { message("Computing spatial coexpression modules...") @@ -1503,7 +1504,7 @@ initHMRF_V2 <- return_gobject = FALSE ) - expr_values <- t(meta.genes@enrichDT[, 1:k.sp]) + expr_values <- t(meta.genes@enrichDT[, seq_len(k.sp)]) colnames(expr_values) <- unlist( meta.genes@enrichDT[, "cell_ID"]) rownames(expr_values) <- paste0( @@ -1538,7 +1539,7 @@ initHMRF_V2 <- ncol.nei <- max(table(c(spatial_network$to, spatial_network$from))) nei <- matrix(-1, ncol = ncol.nei, nrow = numcell) rownames(nei) <- rownames(y) - for (i in 1:numcell) { + for (i in seq_len(numcell)) { nei.i <- c(spatial_network$from[spatial_network$to == rownames(nei)[i]], spatial_network$to[spatial_network$from == rownames(nei)[i]]) @@ -1549,12 +1550,12 @@ initHMRF_V2 <- numnei <- as.integer(rowSums(nei != (-1))) nn <- nei numedge <- 0 - for (i in 1:numcell) { + for (i in seq_len(numcell)) { numedge <- numedge + length(nn[i, nn[i, ] != -1]) } edgelist <- matrix(0, nrow = numedge, ncol = 2) edge_ind <- 1 - for (i in 1:numcell) { + for (i in seq_len(numcell)) { neighbors <- nn[i, nn[i, ] != -1] for (j in seq_along(neighbors)) { edgelist[edge_ind, ] <- c(i, neighbors[j]) @@ -1585,7 +1586,7 @@ initHMRF_V2 <- nstart = nstart ) mu <- t(kk$centers) - lclust <- lapply(1:k, function(x) which(kk$cluster == x)) + lclust <- lapply(seq_len(k), function(x) which(kk$cluster == x)) } else { ##### need to double check leiden and louvain cluster functions gobject@dimension_reduction$cells$spatial <- NULL @@ -1642,7 +1643,7 @@ initHMRF_V2 <- damp <- array(0, c(k)) sigma <- array(0, c(m, m, k)) - for (i in 1:k) { + for (i in seq_len(k)) { sigma[, , i] <- cov(y[lclust[[i]], ]) di <- smfishHmrf::findDampFactor( sigma[, , i], @@ -1749,14 +1750,14 @@ doHMRF_V2 <- function(HMRF_init_obj, betas = NULL) { if (is.null(betas)) { beta_seq <- max(ceiling(ncol(y) / 10), 2) cat(paste0("Default value beta = ", beta_seq, " is used...")) - } else if (length(betas) != 3 || (sum(betas[1:3] < 0) > 0)) { + } else if (length(betas) != 3 || (sum(betas[seq_len(3)] < 0) > 0)) { stop("please provide betas as a vector of 3 non-negative numbers (initial value, nicrement, total iteration number)") } else { beta_init <- betas[1] beta_increment <- betas[2] beta_num_iter <- betas[3] - beta_seq <- (1:beta_num_iter - 1) * beta_increment + beta_init + beta_seq <- (seq_len(beta_num_iter) - 1) * beta_increment + beta_init beta_seq <- sort(unique(c(0, beta_seq))) } diff --git a/R/spatial_enrichment.R b/R/spatial_enrichment.R index f3082a796..e9e0d7848 100644 --- a/R/spatial_enrichment.R +++ b/R/spatial_enrichment.R @@ -341,7 +341,7 @@ makeSignMatrixRank <- function(sc_matrix, sign_matrix <- sig_gene[interGene, available_ct] ct_gene_counts <- NULL - for (i in 1:dim(sign_matrix)[2]) { + for (i in seq_len(dim(sign_matrix)[2])) { a <- length(which(sign_matrix[, i] == 1)) ct_gene_counts <- c(ct_gene_counts, a) } @@ -352,7 +352,7 @@ makeSignMatrixRank <- function(sc_matrix, gene_num <- uniq_ct_gene_counts[i] all_sample_names <- NULL all_sample_list <- NULL - for (j in 1:ntimes) { + for (j in seq_len(ntimes)) { set.seed(j) random_gene <- sample(rownames( gobject@expression$rna$normalized), gene_num, replace = FALSE) @@ -466,7 +466,7 @@ runPAGEEnrich_OLD <- function(gobject, # get enrichment scores enrichment <- matrix( data = NA, nrow = dim(filterSig)[2], ncol = length(cellColMean)) - for (i in (1:dim(filterSig)[2])) { + for (i in seq_len(dim(filterSig)[2])) { signames <- rownames(filterSig)[which(filterSig[, i] == 1)] sigColMean <- apply(geneFold[signames, ], 2, mean) m <- length(signames) @@ -527,7 +527,7 @@ runPAGEEnrich_OLD <- function(gobject, ntimes = n_times ) - for (i in 1:dim(filter_sign_matrix)[2]) { + for (i in seq_len(dim(filter_sign_matrix)[2])) { length_gene <- length(which(filter_sign_matrix[, i] == 1)) join_gene_with_length <- paste("gene_num_", length_gene, sep = "") mean_i <- as.numeric(as.character( @@ -613,7 +613,7 @@ runPAGEEnrich_OLD <- function(gobject, lost_cell_types_DT <- detected_DT[V1 <= min_overlap_genes] if (nrow(lost_cell_types_DT) > 0) { - for (row in 1:nrow(lost_cell_types_DT)) { + for (row in seq_len(nrow(lost_cell_types_DT))) { output <- paste0( "Warning, ", lost_cell_types_DT[row][["Var2"]], " only has ", lost_cell_types_DT[row][["V1"]], @@ -684,13 +684,13 @@ runPAGEEnrich_OLD <- function(gobject, ## 2. first create the random samples all together ## cell_type_list <- list() perm_type_list <- list() - for (row in 1:nrow(sample_intrs)) { + for (row in seq_len(nrow(sample_intrs))) { cell_type <- sample_intrs[row][["cell_type"]] nr_genes <- as.numeric(sample_intrs[row][["nr_markers"]]) gene_list <- list() perm_list <- list() - for (i in 1:n_times) { + for (i in seq_len(n_times)) { sampled_genes <- sample(rownames(expr_values), size = nr_genes) gene_list[[i]] <- sampled_genes perm_list[[i]] <- rep(paste0("p_", i), nr_genes) @@ -728,7 +728,7 @@ runPAGEEnrich_OLD <- function(gobject, all_perms <- unique(perm_round) all_perms_num <- seq_along(all_perms) names(all_perms_num) <- all_perms - group_labels <- paste0("group_", 1:nr_groups) + group_labels <- paste0("group_", seq_len(nr_groups)) groups_vec <- cut( all_perms_num, breaks = nr_groups, labels = group_labels) names(all_perms) <- groups_vec @@ -999,7 +999,7 @@ PAGEEnrich <- function(...) { #' @keywords internal .do_rank_permutation <- function(sc_gene, n) { random_df <- data.frame(matrix(ncol = n, nrow = length(sc_gene))) - for (i in 1:n) { + for (i in seq_len(n)) { set.seed(i) random_rank <- sample( seq_along(sc_gene), length(sc_gene), replace = FALSE) @@ -1145,7 +1145,7 @@ runRankEnrich <- function(gobject, rownames(rankFold) <- rownames(expr_values[]) colnames(rankFold) <- colnames(expr_values[]) - for (i in (1:dim(sign_matrix)[2])) { + for (i in seq_len(dim(sign_matrix)[2])) { signames <- rownames(sign_matrix)[which(sign_matrix[, i] > 0)] interGene <- intersect(signames, rownames(rankFold)) filterSig <- sign_matrix[interGene, ] @@ -1156,9 +1156,9 @@ runRankEnrich <- function(gobject, vectorX <- rep(NA, dim(filterRankFold)[2]) - for (j in (1:dim(filterRankFold)[2])) { + for (j in seq_len(dim(filterRankFold)[2])) { toprpb <- sort(rpb[, j], decreasing = TRUE) - zscore <- sum(toprpb[1:num_agg]) + zscore <- sum(toprpb[seq_len(num_agg)]) vectorX[j] <- zscore } enrichment[i, ] <- vectorX @@ -1387,12 +1387,12 @@ runHyperGeometricEnrich <- function(gobject, ncol = dim(expbinaryOverlap)[2] ) - for (i in (1:dim(inter_sign_matrix)[2])) { + for (i in seq_len(dim(inter_sign_matrix)[2])) { signames <- rownames(inter_sign_matrix)[ which(inter_sign_matrix[, i] == 1)] vectorX <- NULL - for (j in (1:dim(expbinaryOverlap)[2])) { + for (j in seq_len(dim(expbinaryOverlap)[2])) { cellsiggene <- names(expbinaryOverlap[ which(expbinaryOverlap[, j] == 1), j]) x <- length(intersect(cellsiggene, signames)) @@ -2505,7 +2505,7 @@ spot_deconvolution <- function(expr, constant_J <- find_dampening_constant( select_sig_exp, all_exp, solution_all_exp) ###### deconvolution for each spot - for (k in 1:(dim(cluster_cell_exp)[2])) { + for (k in seq_len(dim(cluster_cell_exp)[2])) { B <- Matrix::as.matrix(cluster_cell_exp[, k]) ct_spot_k <- rownames(cluster_i_matrix)[ which(cluster_i_matrix[, k] == 1)] @@ -2598,7 +2598,7 @@ enrich_analysis <- function(expr_values, # get enrichment scores enrichment <- matrix( data = NA, nrow = dim(filterSig)[2], ncol = length(cellColMean)) - for (i in (1:dim(filterSig)[2])) { + for (i in seq_len(dim(filterSig)[2])) { signames <- rownames(filterSig)[which(filterSig[, i] == 1)] sigColMean <- apply(geneFold[signames, ], 2, mean) m <- length(signames) @@ -2637,7 +2637,7 @@ optimize_deconvolute_dwls <- function(exp, solution_all_exp <- solve_OLS_internal(S, all_exp[Genes]) constant_J <- find_dampening_constant(S, all_exp[Genes], solution_all_exp) - for (j in 1:(dim(subBulk)[2])) { + for (j in seq_len(dim(subBulk)[2])) { B <- subBulk[, j] if (sum(B) > 0) { solDWLS <- optimize_solveDampenedWLS(S, B, constant_J) @@ -2715,13 +2715,13 @@ find_dampening_constant <- function(S, # try multiple values of the dampening constant (multiplier) # for each, calculate the variance of the dampened weighted solution for # a subset of genes - for (j in 1:ceiling(log2(max(wsScaledMinusInf)))) { + for (j in seq_len(ceiling(log2(max(wsScaledMinusInf))))) { multiplier <- 1 * 2^(j - 1) wsDampened <- wsScaled wsDampened[which(wsScaled > multiplier)] <- multiplier solutions <- NULL - seeds <- c(1:100) - for (i in 1:100) { + seeds <- seq_len(100) + for (i in seq_len(100)) { set.seed(seeds[i]) # make nondeterministic subset <- sample(length(ws), size = length(ws) * 0.5) # randomly select half of gene set diff --git a/R/spatial_genes.R b/R/spatial_genes.R index e125342f7..dfb89d5b8 100644 --- a/R/spatial_genes.R +++ b/R/spatial_genes.R @@ -346,7 +346,7 @@ NULL spatial_network_min <- spatial_network[, .(from, to)] - all_colindex <- 1:ncol(bin_matrix) + all_colindex <- seq_len(ncol(bin_matrix)) names(all_colindex) <- colnames(bin_matrix) # code for possible combinations @@ -358,7 +358,7 @@ NULL data = NA, nrow = nrow(bin_matrix), ncol = nrow(spatial_network_min)) ## 1. summarize results for each edge in the network - for (row_i in 1:nrow(spatial_network_min)) { + for (row_i in seq_len(nrow(spatial_network_min))) { from_id <- spatial_network_min[row_i][["from"]] to_id <- spatial_network_min[row_i][["to"]] @@ -378,7 +378,7 @@ NULL ## 2. calculate the frequencies of possible combinations ## # '0-0' = 1, '0-1' = 2, '1-0' = 3 and '1-1' = 4 - for (row_i in 1:nrow(matrix_res)) { + for (row_i in seq_len(nrow(matrix_res))) { x <- matrix_res[row_i, ] x <- factor(x, levels = c(1, 2, 3, 4)) tabres <- as.vector(table(x)) @@ -387,7 +387,7 @@ NULL } rownames(table_res) <- rownames(matrix_res) - colnames(table_res) <- 1:4 + colnames(table_res) <- seq_len(4) rable_resDT <- data.table::as.data.table(table_res) rable_resDT[, feats := rownames(table_res)] @@ -542,13 +542,14 @@ NULL } groups <- ceiling(nrow(bin_matrix) / group_size) - cut_groups <- cut(1:nrow(bin_matrix), breaks = groups, labels = 1:groups) + cut_groups <- cut(seq_len(nrow(bin_matrix)), breaks = groups, + labels = seq_len(groups)) if (any(table(cut_groups) == 1)) { stop("With group size = ", group_size, " you have a single gene in a group. Manually pick another group size") } - indexes <- 1:nrow(bin_matrix) + indexes <- seq_len(nrow(bin_matrix)) names(indexes) <- cut_groups @@ -2400,7 +2401,7 @@ spark <- function(gobject, ## create SPARK object for analysis and filter out lowly expressed genes sobject <- SPARK::CreateSPARKObject( counts = expr, - location = locs[, 1:2], + location = locs[, seq_len(2)], percentage = percentage, min_total_counts = min_count ) @@ -2924,7 +2925,7 @@ showPatternGenes <- function(gobject, !is.na(get(selected_PC))][order(get(selected_PC))] subset <- gene_cor_DT[ - c(1:top_neg_genes, (nrow( + c(seq_len(top_neg_genes), (nrow( gene_cor_DT) - top_pos_genes):nrow(gene_cor_DT))] subset[, gene_ID := factor(gene_ID, gene_ID)] @@ -3000,7 +3001,8 @@ selectPatternGenes <- function(spatPatObj, gene_cor_DT_m[, top_pos_rank := rank(value), by = "variable"] gene_cor_DT_m[, top_neg_rank := rank(-value), by = "variable"] selection <- gene_cor_DT_m[ - top_pos_rank %in% 1:top_pos_genes | top_neg_rank %in% 1:top_neg_genes] + top_pos_rank %in% seq_len(top_pos_genes) | + top_neg_rank %in% seq_len(top_neg_genes)] # filter on min correlation selection <- selection[value > min_pos_cor | value < min_neg_cor] @@ -4254,7 +4256,7 @@ getBalancedSpatCoexpressionFeats <- function(spatCorObject, maximum_to_use <- maximum } - selected_feats <- rnkcombined[1:maximum_to_use][["feat_id"]] + selected_feats <- rnkcombined[seq_len(maximum_to_use)][["feat_id"]] clus_id <- rep(clus, length(selected_feats)) names(clus_id) <- selected_feats @@ -4309,7 +4311,7 @@ getBalancedSpatCoexpressionFeats <- function(spatCorObject, maximum_to_use <- maximum } - selected_feats <- names(informed_subset[1:maximum_to_use]) + selected_feats <- names(informed_subset[seq_len(maximum_to_use)]) clus_id <- rep(clus, length(selected_feats)) names(clus_id) <- selected_feats @@ -4868,7 +4870,7 @@ run_spatial_sim_tests_multi <- function(gobject, if (verbose) message("start with ", prob_i) rep_list <- list() - for (rep_i in 1:reps) { + for (rep_i in seq_len(reps)) { if (verbose) message("repetition = ", rep_i) diff --git a/R/spatial_interaction.R b/R/spatial_interaction.R index cb9f6c5f0..9073f3d5c 100644 --- a/R/spatial_interaction.R +++ b/R/spatial_interaction.R @@ -51,7 +51,7 @@ make_simulated_network <- function(gobject, spatial_network_annot$to_cell_type) middle_point <- length(all_cell_type) / 2 - for (sim in 1:number_of_simulations) { + for (sim in seq_len(number_of_simulations)) { if (set_seed == TRUE) { seed_number <- seed_number + sim set.seed(seed = seed_number) @@ -60,7 +60,7 @@ make_simulated_network <- function(gobject, reshuffled_all_cell_type <- sample( x = all_cell_type, size = length(all_cell_type), replace = FALSE) - new_from_cell_type <- reshuffled_all_cell_type[1:middle_point] + new_from_cell_type <- reshuffled_all_cell_type[seq_len(middle_point)] s1_list[[sim]] <- new_from_cell_type new_to_cell_type <- reshuffled_all_cell_type[ @@ -70,7 +70,7 @@ make_simulated_network <- function(gobject, s1_vector <- do.call("c", s1_list) s2_vector <- do.call("c", s2_list) - round_vector <- rep(x = 1:number_of_simulations, each = length_ints) + round_vector <- rep(x = seq_len(number_of_simulations), each = length_ints) round_vector <- paste0("sim", round_vector) # data.table variables @@ -80,7 +80,7 @@ make_simulated_network <- function(gobject, s1 = s1_vector, s2 = s2_vector, round = round_vector) uniq_sim_comb <- unique(sample_dt[, .(s1, s2)]) uniq_sim_comb[, unified_int := paste( - sort(c(s1, s2)), collapse = "--"), by = 1:nrow(uniq_sim_comb)] + sort(c(s1, s2)), collapse = "--"), by = seq_len(nrow(uniq_sim_comb))] sample_dt[uniq_sim_comb, unified_int := unified_int, on = c( s1 = "s1", s2 = "s2")] sample_dt[, type_int := ifelse(s1 == s2, "homo", "hetero")] @@ -190,7 +190,8 @@ cellProximityEnrichment <- function(gobject, minimum_simulations <- unique_ints[rep( seq_len(nrow(unique_ints)), number_of_simulations), ] minimum_simulations[, round := rep( - paste0("sim", 1:number_of_simulations), each = nrow(unique_ints))] + paste0("sim", seq_len(number_of_simulations)), + each = nrow(unique_ints))] minimum_simulations[, N := 0] table_sim_minimum_results <- rbind(table_sim_results, minimum_simulations) @@ -312,7 +313,7 @@ cellProximityEnrichment <- function(gobject, # order table_mean_results_dc <- table_mean_results_dc[order(-PI_value)] - table_mean_results_dc[, int_ranking := 1:.N] + table_mean_results_dc[, int_ranking := seq_len(.N)] return(list(raw_sim_table = table_results, enrichm_res = table_mean_results_dc)) @@ -698,7 +699,7 @@ NULL seed_number_list <- seed_number:(seed_number + (n - 1)) } - result <- lapply(X = 1:n, FUN = function(x) { + result <- lapply(X = seq_len(n), FUN = function(x) { seed_number <- seed_number_list[x] perm_rand <- .do_permuttest_random( @@ -2296,7 +2297,8 @@ average_feat_feat_expression_in_groups <- function(gobject, lig_test <- data.table::as.data.table( reshape2::melt(ligand_match, measure.vars = all_ligand_cols)) lig_test[, ligand := rep(rownames(ligand_match), ncol(ligand_match))] - lig_test[, ligand := strsplit(ligand, "\\.")[[1]][1], by = 1:nrow(lig_test)] + lig_test[, ligand := strsplit(ligand, "\\.")[[1]][1], + by = seq_len(nrow(lig_test))] lig_test[, LR_comb := rep(LR_pairs, ncol(ligand_match))] setnames(lig_test, "value", "lig_expr") setnames(lig_test, "variable", "lig_cell_type") @@ -2306,7 +2308,7 @@ average_feat_feat_expression_in_groups <- function(gobject, receptor_match, measure.vars = all_receptor_cols)) rec_test[, receptor := rep(rownames(receptor_match), ncol(receptor_match))] rec_test[, receptor := strsplit( - receptor, "\\.")[[1]][1], by = 1:nrow(rec_test)] + receptor, "\\.")[[1]][1], by = seq_len(nrow(rec_test))] rec_test[, LR_comb := rep(LR_pairs, ncol(receptor_match))] setnames(rec_test, "value", "rec_expr") setnames(rec_test, "variable", "rec_cell_type") @@ -2436,7 +2438,7 @@ exprCellCellcom <- function(gobject, # not yet available - for (sim in 1:random_iter) { + for (sim in seq_len(random_iter)) { if (verbose == TRUE) cat("simulation ", sim) @@ -2582,7 +2584,7 @@ exprCellCellcom <- function(gobject, set.seed(seed = seed_number) } sub_sample_ids <- possible_metadata[get(cluster_column) == uniq_type][ - sample(x = 1:.N, size = length_random)][["cell_ID"]] + sample(x = seq_len(.N), size = length_random)][["cell_ID"]] sample_ids[[i]] <- sub_sample_ids } return(unlist(sample_ids)) @@ -2789,7 +2791,7 @@ specificCellCellcommunicationScores <- function(gobject, ## simulations ## - for (sim in 1:random_iter) { + for (sim in seq_len(random_iter)) { if (verbose == TRUE) cat("simulation ", sim) # get random ids and subset @@ -3034,7 +3036,7 @@ spatCellCellcom <- function(gobject, ## parallel option ## if (do_parallel == TRUE) { savelist <- lapply_flex( - X = 1:nrow(combn_DT), future.seed = TRUE, + X = seq_len(nrow(combn_DT)), future.seed = TRUE, cores = cores, fun = function(row) { cell_type_1 <- combn_DT[row][["V1"]] cell_type_2 <- combn_DT[row][["V2"]] @@ -3064,7 +3066,7 @@ spatCellCellcom <- function(gobject, savelist <- list() countdown <- nrow(combn_DT) - for (row in 1:nrow(combn_DT)) { + for (row in seq_len(nrow(combn_DT))) { cell_type_1 <- combn_DT[row][["V1"]] cell_type_2 <- combn_DT[row][["V2"]] diff --git a/R/spatial_interaction_spot.R b/R/spatial_interaction_spot.R index 8360f8da0..699df95b2 100644 --- a/R/spatial_interaction_spot.R +++ b/R/spatial_interaction_spot.R @@ -164,9 +164,9 @@ NULL proximity_dt[, V1 := internal + external] proximity_dt[, s1 := strsplit(as.character( - unified_int), split = "--")[[1]][1], by = 1:nrow(proximity_dt)] + unified_int), split = "--")[[1]][1], by = seq_len(nrow(proximity_dt))] proximity_dt[, s2 := strsplit(as.character( - unified_int), split = "--")[[1]][2], by = 1:nrow(proximity_dt)] + unified_int), split = "--")[[1]][2], by = seq_len(nrow(proximity_dt))] proximity_dt[, type_int := ifelse(s1 == s2, "homo", "hetero")] proximity_dt <- proximity_dt[ , c("unified_int", "type_int", "V1", "external", "internal")] @@ -300,7 +300,7 @@ cellProximityEnrichmentSpots <- function(gobject, # method for get simulation cell-type/cell-type interaction for each round data.table::setnames(sample_dt, old = c("s1", "s2"), new = c("from", "to")) table_sim_results <- NULL - for (sim in 1:number_of_simulations) { + for (sim in seq_len(number_of_simulations)) { r <- paste0("sim", sim) sim_pairs <- sample_dt[round == r, c("from", "to")] @@ -417,7 +417,7 @@ cellProximityEnrichmentSpots <- function(gobject, # order table_mean_results_dc <- table_mean_results_dc[order(-PI_value)] - table_mean_results_dc[, int_ranking := 1:.N] + table_mean_results_dc[, int_ranking := seq_len(.N)] return(list( raw_sim_table = table_results, enrichm_res = table_mean_results_dc)) @@ -472,7 +472,7 @@ featExpDWLS <- function(gobject, ) average_exp <- as.matrix(ave_celltype_exp) - for (spot_i in 1:nrow(dwls_values)) { + for (spot_i in seq_len(nrow(dwls_values))) { spot <- dwls_values[spot_i, 1] spot_dwls <- dwls_values[spot_i, -1] data.table::setDF(spot_dwls) @@ -602,7 +602,8 @@ cellProximityEnrichmentEachSpot <- function(gobject, cts <- colnames(dwls_values) ct_pairs <- data.table::data.table( V1 = rep(cts, each = length(cts)), V2 = rep(cts, length(cts))) - ct_pairs[, unified_int := paste0(V1, "--", V2), by = 1:nrow(ct_pairs)] + ct_pairs[, unified_int := paste0(V1, "--", V2), + by = seq_len(nrow(ct_pairs))] unified_int <- ct_pairs$unified_int @@ -835,7 +836,7 @@ NULL seed_number_list <- seed_number:(seed_number + (n - 1)) } - result <- lapply_flex(X = 1:n, cores = cores, fun = function(x) { + result <- lapply_flex(X = seq_len(n), cores = cores, fun = function(x) { seed_number <- seed_number_list[x] perm_rand <- .do_permuttest_random_spot( @@ -1169,9 +1170,9 @@ findICFSpot <- function(gobject, # compute correlation between features and cell-types to find ICFs all_ints <- data.table::data.table(unified_int = rownames(proximityMat)) all_ints[, cell_type := strsplit( - as.character(unified_int), "--")[[1]][1], by = 1:nrow(all_ints)] + as.character(unified_int), "--")[[1]][1], by = seq_len(nrow(all_ints))] all_ints[, int_cell_type := strsplit( - as.character(unified_int), "--")[[1]][2], by = 1:nrow(all_ints)] + as.character(unified_int), "--")[[1]][2], by = seq_len(nrow(all_ints))] # exact spatial_enrichment matrix dwls_values <- getSpatialEnrichment( @@ -1421,7 +1422,7 @@ plotICFSpot <- function(gobject, cell_type == source_type][int_cell_type %in% neighbor_types] tempDT[, features := factor(feats, levels = detected_features)] tempDT[, group := names(ICF_features[ - ICF_features == feats]), by = 1:nrow(tempDT)] + ICF_features == feats]), by = seq_len(nrow(tempDT))] if (is.null(cell_color_code)) { @@ -1943,7 +1944,7 @@ plotCellProximityFeatSpot <- function(gobject, all_cell_ids <- colnames(expr_residual) ## simulations ## - for (sim in 1:random_iter) { + for (sim in seq_len(random_iter)) { if (verbose == TRUE) cat("simulation ", sim, "\n") # get random ids and subset @@ -2192,14 +2193,14 @@ spatCellCellcomSpots <- function(gobject, ## get all combinations between cell types combn_DT <- data.table::data.table(LR_cell_comb = rownames(proximityMat)) combn_DT[, V1 := strsplit( - LR_cell_comb, "--")[[1]][1], by = 1:nrow(combn_DT)] + LR_cell_comb, "--")[[1]][1], by = seq_len(nrow(combn_DT))] combn_DT[, V2 := strsplit( - LR_cell_comb, "--")[[1]][2], by = 1:nrow(combn_DT)] + LR_cell_comb, "--")[[1]][2], by = seq_len(nrow(combn_DT))] ## parallel option ## if (do_parallel == TRUE) { savelist <- lapply_flex( - X = 1:nrow(combn_DT), cores = cores, fun = function(row) { + X = seq_len(nrow(combn_DT)), cores = cores, fun = function(row) { cell_type_1 <- combn_DT[row][["V1"]] cell_type_2 <- combn_DT[row][["V2"]] @@ -2229,7 +2230,7 @@ spatCellCellcomSpots <- function(gobject, savelist <- list() countdown <- nrow(combn_DT) - for (row in 1:nrow(combn_DT)) { + for (row in seq_len(nrow(combn_DT))) { cell_type_1 <- combn_DT[row][["V1"]] cell_type_2 <- combn_DT[row][["V2"]] diff --git a/R/spatial_interaction_visuals.R b/R/spatial_interaction_visuals.R index 136d12c26..a373502b0 100644 --- a/R/spatial_interaction_visuals.R +++ b/R/spatial_interaction_visuals.R @@ -116,10 +116,10 @@ cellProximityHeatmap <- function(gobject, enrich_res[, first_type := strsplit( x = as.character(unified_int), split = "--")[[1]][1], - by = 1:nrow(enrich_res)] + by = seq_len(nrow(enrich_res))] enrich_res[, second_type := strsplit( x = as.character(unified_int), split = "--")[[1]][2], - by = 1:nrow(enrich_res)] + by = seq_len(nrow(enrich_res))] # create matrix enrich_mat <- data.table::dcast.data.table( @@ -255,9 +255,11 @@ cellProximityNetwork <- function(gobject, CPscores <- CPscore[["enrichm_res"]] CPscores[, cell_1 := strsplit( - as.character(unified_int), split = "--")[[1]][1], by = 1:nrow(CPscores)] + as.character(unified_int), split = "--")[[1]][1], + by = seq_len(nrow(CPscores))] CPscores[, cell_2 := strsplit( - as.character(unified_int), split = "--")[[1]][2], by = 1:nrow(CPscores)] + as.character(unified_int), split = "--")[[1]][2], + by = seq_len(nrow(CPscores))] # create igraph with enrichm as weight edges igd <- igraph::graph_from_data_frame( @@ -1763,7 +1765,8 @@ plotInteractionChangedFeats <- function(gobject, tempDT <- ICFscores[feats %in% all_feats][cell_type == source_type][ int_cell_type %in% neighbor_types] tempDT[, feats := factor(feats, levels = detected_feats)] - tempDT[, group := names(ICF_feats[ICF_feats == feats]), by = 1:nrow(tempDT)] + tempDT[, group := names(ICF_feats[ICF_feats == feats]), + by = seq_len(nrow(tempDT))] if (is.null(cell_color_code)) { @@ -2742,16 +2745,16 @@ plotRankSpatvsExpr <- function(gobject, rnk_list <- list() spt_list <- list() - for (rnk in 1:total_rnks) { + for (rnk in seq_len(total_rnks)) { mytab <- table(cut(sort(combCC[get(expr_rnk_column) == rnk][[ spat_rnk_column]]), breaks = seq(0, total_rnks, 1), - labels = c(1:total_rnks))) + labels = seq_len(total_rnks))) rnk_list[[rnk]] <- mytab spt_list[[rnk]] <- names(mytab) } rnk_res <- data.table::as.data.table(do.call("rbind", rnk_list)) - rnk_res[, spt_rank := 1:total_rnks] + rnk_res[, spt_rank := seq_len(total_rnks)] rnk_res_m <- data.table::melt.data.table(rnk_res, id.vars = "spt_rank") rnk_res_m[, spt_rank := as.numeric(spt_rank)] @@ -2827,7 +2830,7 @@ plotRankSpatvsExpr <- function(gobject, mergeDT_filt <- combCC[get(first_col) == 1] mymat <- matrix(data = NA, nrow = max(combCC[[second_col]]), ncol = 2) - for (i in 1:max(combCC[[second_col]])) { + for (i in seq_len(max(combCC[[second_col]]))) { mergeDT_filt[, concord := ifelse(get(second_col) <= i, "yes", "no")] mytable <- table(mergeDT_filt$concord) @@ -2843,7 +2846,7 @@ plotRankSpatvsExpr <- function(gobject, mymatDT <- data.table::as.data.table(mymat) colnames(mymatDT) <- c("concord", "not_concord") mymatDT[, perc := 100 * (concord / (concord + not_concord))] - mymatDT[, secondrank := 1:nrow(mymatDT)] + mymatDT[, secondrank := seq_len(nrow(mymatDT))] mymatDT[, secondrank_perc := (secondrank / max(secondrank)) * 100] # percentage explained diff --git a/R/variable_genes.R b/R/variable_genes.R index 39e12568c..c7db7fb44 100644 --- a/R/variable_genes.R +++ b/R/variable_genes.R @@ -24,7 +24,7 @@ expr_groups <- cut( x = feat_in_cells_detected$mean_expr, breaks = expr_group_breaks, - labels = paste0("group_", 1:nr_expression_groups), + labels = paste0("group_", seq_len(nr_expression_groups)), include.lowest = TRUE ) feat_in_cells_detected[, expr_groups := expr_groups] @@ -65,7 +65,7 @@ feat_in_cells_detected$pred_cov_feats <- stats::predict( loess_model_sample, newdata = feat_in_cells_detected) feat_in_cells_detected[, cov_diff := get(var_col) - pred_cov_feats, - by = 1:nrow(feat_in_cells_detected)] + by = seq_len(nrow(feat_in_cells_detected))] data.table::setorder(feat_in_cells_detected, -cov_diff) feat_in_cells_detected[, selected := ifelse( cov_diff > difference_in_cov, "yes", "no")] @@ -106,7 +106,7 @@ dt_res <- data.table::data.table(feats = names(test), var = test) if (!is.null(var_number) & is.numeric(var_number)) { - dt_res[, selected := 1:.N] + dt_res[, selected := seq_len(.N)] dt_res[, selected := ifelse(selected <= var_number, "yes", "no")] } else { dt_res[, selected := ifelse(var >= var_threshold, "yes", "no")] @@ -116,7 +116,7 @@ if (isTRUE(show_plot) || isTRUE(return_plot) || isTRUE(save_plot)) { - dt_res[, rank := 1:.N] + dt_res[, rank := seq_len(.N)] pl <- .create_calc_var_hvf_plot(dt_res) @@ -336,7 +336,8 @@ calculateHVF <- function(gobject, if (!is.null(random_subset)) { if (isTRUE(set_seed)) set.seed(seed = seed_number) - random_selection <- sort(sample(1:ncol(expr_values), random_subset)) + random_selection <- sort(sample( + seq_len(ncol(expr_values)), random_subset)) expr_values <- expr_values[, random_selection] if (isTRUE(set_seed)) GiottoUtils::random_seed() diff --git a/R/wnn.R b/R/wnn.R index af8be2427..293e5d645 100644 --- a/R/wnn.R +++ b/R/wnn.R @@ -549,7 +549,7 @@ runIntegratedUMAP <- function(gobject, shared <- NULL nn_network_dt <- data.table::data.table( from = rep( - 1:nrow(nn_network$id), + seq_len(nrow(nn_network$id)), k ), to = as.vector(nn_network$id),