CodexBloom - Programming Q&A Platform

Unexpected NaN results when performing vectorized calculations with `sweep()` on a matrix in R 4.3

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
R matrix data-manipulation sweep

Could someone explain I'm getting frustrated with I'm dealing with I'm trying to compute row-wise z-scores for a matrix using the `sweep()` function in R 4.3, but I'm running into unexpected NaN values in my output... Here's what I've been working with: ```R # Sample data set.seed(123) mat <- matrix(rnorm(12), nrow = 4) # Compute means and standard deviations row_means <- rowMeans(mat) row_sds <- apply(mat, 1, sd) # Attempt to calculate z-scores z_scores <- sweep(mat, 1, row_means, "-") # I expected the next line to work, but it returns NaN z_scores <- sweep(z_scores, 1, row_sds, "/") ``` When I run this code, the second sweep call produces a matrix filled with NaN values. I've checked that `row_sds` does not contain zero values, yet I still encounter this scenario. I even tried wrapping `row_sds` with `ifelse()` to replace zeros with small values, but I still get NaN in my results. I also attempted using `scale()` directly, which worked fine, but I want to understand why `sweep()` is failing here. Could it be related to how R handles vector recycling or the dimensions of my data? Any insights on how to avoid this scenario would be greatly appreciated! I'd really appreciate any guidance on this. I'm using R LTS in this project. I'm developing on Ubuntu 22.04 with R. I'm developing on Windows 10 with R. Any suggestions would be helpful.