You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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=FALSE when 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. colMeans requires a data frame or matrix, so this step breaks the input it needs.
  • Unhandled non-numeric value: The B6 in column D can't be converted to a number directly—we need to handle this by turning it into an NA that colMeans can 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:25:10