R语言中对列表元素执行t检验报错:'missing value where TRUE/FALSE needed'问题排查求助
Hey there, let's break down this error you're hitting with your t-test code in R.
What's causing the error?
The error message missing value where TRUE/FALSE needed comes from an internal check inside t.test(). Specifically, the function tries to run this conditional check:
if (stderr < 10 * .Machine$double.eps * abs(mx)) stop("data are essentially constant")
But instead of getting a TRUE/FALSE result, the expression returns NA. This means either stderr (the standard error of your sample) or mx (the sample mean) is an NA value—so R can't evaluate the condition properly.
Looking at your code, here are the most likely culprits:
Invalid
alternativeparameter
You're passingalternative = "two"tot.test(), but the only valid values for this argument are"two.sided","less", or"greater". Using"two"confuses the function, which can lead to unexpected NA values in internal calculations.Hidden issues in your data (even after NA checks)
Your current checksum(!is.na(...)) > 1ensures you have at least two non-NA values, but it doesn't account for:- Non-numeric values that get converted to NA silently when you run
as.numeric()(like text strings such as "N/A" or empty cells). - Cases where all non-NA values are identical (this would trigger a different error, but combined with the bad parameter, it could lead to this NA issue).
- Rare cases where your data contains
NaN(not justNA), which would make the sample meanmxreturnNaNinstead of a valid number.
- Non-numeric values that get converted to NA silently when you run
Fixes to try:
First, fix the parameter issue—that's the easiest win:
# Replace "two" with the valid "two.sided" t.test(vec_clean, alternative = "two.sided")$p.value
Next, strengthen your data validation to catch edge cases before calling t.test():
sapply(rownames(d), function(i) { # Extract and clean the vector first vec <- as.numeric(d[i, grep("pct_rep", colnames(d))]) vec_clean <- vec[!is.na(vec)] # Only run t-test if: # 1. We have at least 2 valid values # 2. The values aren't all identical (to avoid another t.test error) if (length(vec_clean) > 1 && length(unique(vec_clean)) > 1) { t.test(vec_clean, alternative = "two.sided")$p.value } else { NA } })
Finally, debug to find the exact row causing the problem:
Add a print statement to see which row is failing, then inspect that row's data directly:
sapply(rownames(d), function(i) { vec <- as.numeric(d[i, grep("pct_rep", colnames(d))]) cat("Row:", i, "| Non-NA count:", sum(!is.na(vec)), "| Values:", vec, "\n") # Your existing logic here })
This will help you spot if a specific row has wonky data (like all NAs after conversion, or non-numeric values you missed).
内容的提问来源于stack exchange,提问作者mike ropri

