R语言中colMeans函数无法正常工作的问题求助
Fixing Column Mean Calculation for Your Dummy.txt Dataset
Let's break down why your code isn't working and fix it step by step:
Key Issues in Your Original Code
- Incorrect header setting: You used
header=FALSEwhen reading the data, but your first line (A|B|C|D) is actually the column names. This caused the header to be treated as a data row, messing up all subsequent processing. - Wrong data structure conversion:
as.numeric(as.character(mydata_1))converts the entire data frame into a single numeric vector instead of preserving column structure.colMeansrequires a data frame or matrix, so this step breaks the input it needs. - Unhandled non-numeric value: The
B6in column D can't be converted to a number directly—we need to handle this by turning it into anNAthatcolMeanscan ignore.
Corrected Code
First, read the data properly with the correct header setting:
# Read data, recognizing the first line as column names mydata_1 <- read.delim("Dummy.txt", skipNul = TRUE, sep = "|", header = TRUE, row.names = NULL)
Next, convert each column to numeric type (this will turn non-numeric values like B6 into NA):
# Convert all columns to numeric, preserving data frame structure mydata_1[] <- lapply(mydata_1, function(x) as.numeric(as.character(x)))
Finally, calculate column means while ignoring NA values:
# Compute column means, skipping NA entries colMeans(mydata_1, na.rm = TRUE)
Expected Output
When you run this code, you'll get the correct column means:
A B C D 3.875000 37.250000 149.725000 2.800000
内容的提问来源于stack exchange,提问作者Sharon
相关产品推荐
相关产品推荐

