如何按行计算标准差?rowSds函数执行失败问题求助
Hey there! Let's troubleshoot why your rowSds() call isn't working even though rowMeans() runs fine. Here are the most likely issues and fixes:
1. You're Missing the matrixStats Package
First off, rowSds() isn't part of R's base packages—it belongs to the matrixStats library. If you haven't installed or loaded this package yet, R will throw a "could not find function 'rowSds'" error.
Fix this by:
# Install the package (only need to do this once) install.packages("matrixStats") # Load it before using rowSds() library(matrixStats)
2. Your Data Might Be a Data Frame Instead of a Matrix
While rowMeans() works seamlessly with data frames, rowSds() is optimized for matrix inputs. If your values_for_all object is a data frame, converting it to a matrix will resolve most issues.
Modify your code like this:
# Convert data frame to matrix values_matrix <- as.matrix(values_for_all) # Now calculate row-wise SD SD <- rowSds(values_matrix, na.rm = TRUE)
3. Alternative: Use Base R (No Extra Package Needed)
If you'd rather avoid installing additional packages, you can use apply() with base R's sd() function to get the same result:
SD <- apply(values_for_all, 1, function(x) sd(x, na.rm = TRUE))
This applies the sd() function to each row (the 1 in the second argument specifies rows) and ignores NA values.
Test with Your Sample Data
Let's verify with your input example to make sure it works:
# Recreate your sample data values_for_all <- data.frame( V1 = c(1, 2), V2 = c(0.35, 8.75), V3 = c(0.35, 3.22), V4 = c(4.33, 7.34), V5 = c(0.09, 0.56), V6 = c(4.17, 2.43), V7 = c(0.16, 0.23), V8 = c(9.90, 1.20), V9 = c(15.25, 8.45), V10 = c(0.16, 1.26), V11 = c(2.38, NA), V12 = c(2.55, NA), V13 = c(8.14, 1.24), V14 = c(0.16, 0.16), V15 = c(NA, 2.34), V16 = c(0.16, 0.36) ) # Clean and convert data (your original code) values_for_all[values_for_all == ''] <- NA values_for_all[] <- lapply(values_for_all, as.numeric) # Calculate means (works as expected) values_mean <- rowMeans(values_for_all, na.rm=TRUE) # Calculate SD with matrixStats library(matrixStats) SD_matrixStats <- rowSds(as.matrix(values_for_all), na.rm=TRUE) # Calculate SD with base R SD_baseR <- apply(values_for_all, 1, function(x) sd(x, na.rm = TRUE)) # Both methods give the same result print(SD_matrixStats) print(SD_baseR)
Running this should output the correct row-wise standard deviations for your dataset.
内容的提问来源于stack exchange,提问作者student24

