seurat icon indicating copy to clipboard operation
seurat copied to clipboard

Issue: Error in xtfrm.data.frame(x) when using SpatiallyVariableFeatures function

Open nilesh-iiita opened this issue 1 year ago • 7 comments

Description: I encountered an error while using the selection.method = "moransi" option in the SpatiallyVariableFeatures() function. The error message states: "Error in xtfrm.data.frame(x) : cannot xtfrm data frames." This issue arises when executing the following code:

Steps to reproduce:

Load the brain dataset. Execute the code snippet provided below, which includes the FindSpatiallyVariableFeatures() and SpatiallyVariableFeatures() functions with the selection.method parameter set to "moransi". Observe the error message: "Error in xtfrm.data.frame(x) : cannot xtfrm data frames."

library(Seurat)
library(SeuratData)
library(ggplot2)
library(patchwork)
library(dplyr)
brain <- LoadData("stxBrain", type = "anterior1")
brain <- SCTransform(brain, assay = "Spatial", verbose = FALSE)

# rerun normalization to store sctransform residuals for all genes
brain <- SCTransform(brain, assay = "Spatial", return.only.var.genes = FALSE, verbose = FALSE)
# also run standard log normalization for comparison
brain <- NormalizeData(brain, verbose = FALSE, assay = "Spatial")

# Computes the correlation of the log normalized data and sctransform residuals with the
# number of UMIs
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "Spatial", slot = "data", do.plot = FALSE)
brain <- GroupCorrelation(brain, group.assay = "Spatial", assay = "SCT", slot = "scale.data", do.plot = FALSE)



p1 <- GroupCorrelationPlot(brain, assay = "Spatial", cor = "nCount_Spatial_cor") + ggtitle("Log Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p2 <- GroupCorrelationPlot(brain, assay = "SCT", cor = "nCount_Spatial_cor") + ggtitle("SCTransform Normalization") +
    theme(plot.title = element_text(hjust = 0.5))
p1 + p2
SpatialFeaturePlot(brain, features = c("Hpca", "Ttr"))

library(ggplot2)
plot <- SpatialFeaturePlot(brain, features = c("Ttr")) + theme(legend.text = element_text(size = 0),
    legend.title = element_text(size = 20), legend.key.size = unit(1, "cm"))
# jpeg(filename = "../output/images/spatial_vignette_ttr.jpg", height = 700, width = 1200, quality = 50)
print(plot)
dev.off()
p1 <- SpatialFeaturePlot(brain, features = "Ttr", pt.size.factor = 1)
p2 <- SpatialFeaturePlot(brain, features = "Ttr", alpha = c(0.1, 1))
p1 + p2
brain <- RunPCA(brain, assay = "SCT", verbose = FALSE)
brain <- FindNeighbors(brain, reduction = "pca", dims = 1:30)
brain <- FindClusters(brain, verbose = FALSE)
brain <- RunUMAP(brain, reduction = "pca", dims = 1:30)
p1 <- DimPlot(brain, reduction = "umap", label = TRUE)
p2 <- SpatialDimPlot(brain, label = TRUE, label.size = 3)
p1 + p2
SpatialDimPlot(brain, cells.highlight = CellsByIdentities(object = brain, idents = c(2, 1, 4, 3,
    5, 8)), facet.highlight = TRUE, ncol = 3)
de_markers <- FindMarkers(brain, ident.1 = 5, ident.2 = 6)
SpatialFeaturePlot(object = brain, features = rownames(de_markers)[1:3], alpha = c(0.1, 1), ncol = 3)
brain <- FindSpatiallyVariableFeatures(brain, assay = "SCT", features = VariableFeatures(brain)[1:1000],
    selection.method = "moransi")

Computing Moran's I |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=27s

SpatiallyVariableFeatures(brain, selection.method = "moransi")

Error in xtfrm.data.frame(x) : cannot xtfrm data frames

nilesh-iiita avatar Jun 07 '23 16:06 nilesh-iiita

sessionInfo()

`

R version 4.3.0 Patched (2023-05-02 r84382)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.5

Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.11.0

locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: America/Chicago tzcode source: internal

attached base packages: [1] stats graphics grDevices utils datasets methods base

other attached packages: [1] dplyr_1.1.2 patchwork_1.1.2 ggplot2_3.4.2 stxBrain.SeuratData_0.1.1 ssHippo.SeuratData_3.1.4 SeuratData_0.2.2.9001
[7] Seurat_4.9.9.9045 SeuratObject_4.9.9.9084 sp_1.6-1

loaded via a namespace (and not attached): [1] RColorBrewer_1.1-3 rstudioapi_0.14 jsonlite_1.8.5 magrittr_2.0.3 spatstat.utils_3.0-3
[6] rmarkdown_2.22 farver_2.1.1 zlibbioc_1.46.0 vctrs_0.6.2 ROCR_1.0-11
[11] DelayedMatrixStats_1.22.0 spatstat.explore_3.2-1 RCurl_1.98-1.12 S4Arrays_1.0.4 htmltools_0.5.5
[16] sctransform_0.3.5 parallelly_1.36.0 KernSmooth_2.23-21 htmlwidgets_1.6.2 ica_1.0-3
[21] plyr_1.8.8 plotly_4.10.2 zoo_1.8-12 igraph_1.4.3 mime_0.12
[26] lifecycle_1.0.3 pkgconfig_2.0.3 Matrix_1.5-4.1 R6_2.5.1 fastmap_1.1.1
[31] GenomeInfoDbData_1.2.10 MatrixGenerics_1.12.0 fitdistrplus_1.1-11 future_1.32.0 shiny_1.7.4
[36] digest_0.6.31 colorspace_2.1-0 S4Vectors_0.38.1 tensor_1.5 RSpectra_0.16-1
[41] irlba_2.3.5.1 GenomicRanges_1.52.0 labeling_0.4.2 RcppZiggurat_0.1.6 progressr_0.13.0
[46] fansi_1.0.4 spatstat.sparse_3.0-1 httr_1.4.6 polyclip_1.10-4 abind_1.4-5
[51] compiler_4.3.0 withr_2.5.0 fastDummies_1.6.3 MASS_7.3-60 DelayedArray_0.26.3
[56] rappdirs_0.3.3 tools_4.3.0 lmtest_0.9-40 httpuv_1.6.11 future.apply_1.11.0
[61] Rfast2_0.1.4 goftest_1.2-3 glmGamPoi_1.12.1 glue_1.6.2 nlme_3.1-162
[66] promises_1.2.0.1 grid_4.3.0 Rtsne_0.16 cluster_2.1.4 reshape2_1.4.4
[71] generics_0.1.3 gtable_0.3.3 spatstat.data_3.0-1 tidyr_1.3.0 data.table_1.14.8
[76] XVector_0.40.0 utf8_1.2.3 BiocGenerics_0.46.0 spatstat.geom_3.2-1 RcppAnnoy_0.0.20
[81] ggrepel_0.9.3 RANN_2.6.1 pillar_1.9.0 stringr_1.5.0 limma_3.56.1
[86] spam_2.9-1 RcppHNSW_0.4.1 later_1.3.1 splines_4.3.0 lattice_0.21-8
[91] survival_3.5-5 deldir_1.0-9 tidyselect_1.2.0 miniUI_0.1.1.1 pbapply_1.7-0
[96] knitr_1.43 gridExtra_2.3 IRanges_2.34.0 SummarizedExperiment_1.30.1 scattermore_1.1
[101] stats4_4.3.0 xfun_0.39 Biobase_2.60.0 matrixStats_1.0.0 stringi_1.7.12
[106] yaml_2.3.7 lazyeval_0.2.2 evaluate_0.21 codetools_0.2-19 tibble_3.2.1
[111] cli_3.6.1 uwot_0.1.14 xtable_1.8-4 reticulate_1.29 munsell_0.5.0
[116] Rcpp_1.0.10 GenomeInfoDb_1.36.0 globals_0.16.2 spatstat.random_3.1-5 png_0.1-8
[121] Rfast_2.0.7 parallel_4.3.0 ellipsis_0.3.2 presto_1.0.0 dotCall64_1.0-2
[126] sparseMatrixStats_1.12.0 bitops_1.0-7 listenv_0.9.0 viridisLite_0.4.2 scales_1.2.1
[131] ggridges_0.5.4 leiden_0.4.3 purrr_1.0.1 crayon_1.5.2 rlang_1.1.1
[136] cowplot_1.1.1

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid" width="724" height="561" viewBox="0 0 724 561" class="GND-IWGDF2B GND-IWGDJ2B GND-IWGDH2B"><linearGradient id="gradientFill-1" x1="0" x2="1" y1="0" y2="1" gradientUnits="objectBoundingBox" spreadMethod="pad"></linearGradient><linearGradient id="gradientFill-2" x1="0" x2="1" y1="0" y2="1" gradientUnits="objectBoundingBox" spreadMethod="pad"></linearGradient>
R 4.3.0
·
~/
`

nilesh-iiita avatar Jun 07 '23 16:06 nilesh-iiita

Possible Solution:

SpatiallyVariableFeatures_workaround <- function(object, assay="SCT", selection.method = "moransi") {
  #' This is work around function to replace SeuratObject::SpatiallyVariableFeatures function.
  #' return ranked list of Spatially Variable Features
  
  # Check if object is a Seurat object
  if (!inherits(object, "Seurat")) {
    stop("object must be a Seurat object")
  }

  # Check if assay is a valid assay
  if (!assay %in% names(object@assays)) {
    stop("assay must be a valid assay")
  }
  
  # Extract meta.features from the specified object and assay
  data <- object@assays[[assay]]@meta.features
  
  # Select columns starting with the provided col_prefix
  moransi_cols <- grep(paste0("^", selection.method), colnames(data), value = TRUE)

  # Filter rows where "moransi.spatially.variable" is TRUE
  filtered_data <- data[data[[paste0(selection.method, ".spatially.variable")]], moransi_cols]

  # Sort filtered data by "moransi.spatially.variable.rank" column in ascending order
  sorted_data <- filtered_data[order(filtered_data[[paste0(selection.method, ".spatially.variable.rank")]]), ]

  # Return row names of the sorted data frame
  rownames(sorted_data)
}

head(SpatiallyVariableFeatures_workaround(brain, selection.method = "moransi"), 6)

[1] "Calb2" "Gng4" "Ttr" "S100a5" "Nrgn" "Fabp7" The issue I notice here is that the "Fabp7" is not in the original Vignette.

Please share any suggestions you may have!

nilesh-iiita avatar Jun 07 '23 19:06 nilesh-iiita

Possible Solution:

SpatiallyVariableFeatures_workaround <- function(object, assay="SCT", selection.method = "moransi") {
  #' This is work around function to replace SeuratObject::SpatiallyVariableFeatures function.
  #' return ranked list of Spatially Variable Features
  
  # Check if object is a Seurat object
  if (!inherits(object, "Seurat")) {
    stop("object must be a Seurat object")
  }

  # Check if assay is a valid assay
  if (!assay %in% names(object@assays)) {
    stop("assay must be a valid assay")
  }
  
  # Extract meta.features from the specified object and assay
  data <- object@assays[[assay]]@meta.features
  
  # Select columns starting with the provided col_prefix
  moransi_cols <- grep(paste0("^", selection.method), colnames(data), value = TRUE)

  # Filter rows where "moransi.spatially.variable" is TRUE
  filtered_data <- data[data[[paste0(selection.method, ".spatially.variable")]], moransi_cols]

  # Sort filtered data by "moransi.spatially.variable.rank" column in ascending order
  sorted_data <- filtered_data[order(filtered_data[[paste0(selection.method, ".spatially.variable.rank")]]), ]

  # Return row names of the sorted data frame
  rownames(sorted_data)
}

head(SpatiallyVariableFeatures_workaround(brain, selection.method = "moransi"), 6)

[1] "Calb2" "Gng4" "Ttr" "S100a5" "Nrgn" "Fabp7" The issue I notice here is that the "Fabp7" is not in the original Vignette.

Please share any suggestions you may have!

Because you did not avoid NAs: logical subsetting will always return NAs. Changes should be made.

# Filter rows where "moransi.spatially.variable" is TRUE
filtered_data <- data[
  data[[paste0(selection.method, ".spatially.variable")]] & (!is.na(data[[paste0(selection.method, ".spatially.variable")]])), 
  moransi_cols
]

I also have the same issue in version 5.0.1. Thank you for your solution!!!

lict99 avatar Jan 09 '24 14:01 lict99

Thank you, solved the issue I was encountering

BasMatsuura avatar Mar 23 '24 11:03 BasMatsuura

Hello everyone,

also

top.clusters <- head(SpatiallyVariableFeatures(cortex, selection.method = "moransi"), 4)

gives the same error (Error in xtfrm.data.frame(x) : cannot xtfrm data frames). But using the SpatiallyVariableFeatures_workaround solution gives back:

Error in order(filtered_data[[paste0(selection.method, ".spatially.variable.rank")]]) : argument 1 is not a vector

Is it possible to solve it?

MatteoRiva95 avatar Apr 05 '24 09:04 MatteoRiva95

whien I run filtered_data <- data[

  • data[[paste0(selection.method, ".spatially.variable")]] & (!is.na(data[[paste0(selection.method, ".spatially.variable")]])),
  • moransi_cols
  • ], new issue intercome😧 Error in h(simpleError(msg, call)): Error evaluating argument 'i' while selecting method for function '[': Error evaluating argument 'i' while selecting method for function '[[': object 'selection.method' not found

INeedCNS avatar Jun 18 '24 05:06 INeedCNS

whien I run filtered_data <- data[

  • data[[paste0(selection.method, ".spatially.variable")]] & (!is.na(data[[paste0(selection.method, ".spatially.variable")]])),
  • moransi_cols
  • ], new issue intercome😧 Error in h(simpleError(msg, call)): Error evaluating argument 'i' while selecting method for function '[': Error evaluating argument 'i' while selecting method for function '[[': object 'selection.method' not found

Error message: "object 'selection.method' not found." Did you run this command separately? This command is part of a function as proposed by @nilesh-iiita. Refer to https://github.com/satijalab/seurat/issues/7422#issuecomment-1581369083.

lict99 avatar Jun 18 '24 08:06 lict99