执行线性回归时出错

Error while performing linear regression

我正在尝试对以下数据执行线性回归:-

需要对 Air_weight 和 Water_weight 执行线性回归。

请告诉我如何解决此错误。

这是我试过但出错的代码:-

fit <- lm(Water_Weight~Air_Weight, data=table1)

错误

**Warning messages:
1: In model.response(mf, "numeric") :
  using type = "numeric" with a factor response will be ignored
2: In Ops.factor(y, z$residuals) : ‘-’ not meaningful for factors**



ID  GENDER  Air_Weight    Water_Weight  Body_Fat
01  1       75.60               *        14.17 
02  1       70.70              3.60      13.95 
03  1         *                4.00      8.98 
04  1       95.00              4.30      17.32   
05  1       73.20              3.80      11.50 

您的数据结构存在一些问题,可能是由于您将数据读入 R 的方式所致。最明显的问题是您需要在阅读时使用 na.strings="*" 作为附加参数在您的数据中(使用 read.csv()read.table()),以避免将 Air_WeightWater_Weight 变量转换为因子。

可能还有其他问题,但无法远程诊断。下面是一个示例,说明此方法 可以 工作:

table1 <- read.table(header=TRUE,na.strings="*",text="
ID  GENDER  Air_Weight    Water_Weight  Body_Fat
01  1       75.60               *        14.17 
02  1       70.70              3.60      13.95 
03  1         *                4.00      8.98 
04  1       95.00              4.30      17.32
05  1       73.20              3.80      11.50") 

str(table1)
## 'data.frame':    5 obs. of  5 variables:
##  $ ID          : int  1 2 3 4 5
##  $ GENDER      : int  1 1 1 1 1
##  $ Air_Weight  : num  75.6 70.7 NA 95 73.2
##  $ Water_Weight: num  NA 3.6 4 4.3 3.8
##  $ Body_Fat    : num  14.17 13.95 8.98 17.32 11.5

如果您正在从 CSV 文件中读取数据,您应该使用如下内容:

table1 <- read.csv("my_data_file.csv",na.strings="*")

header=TRUEread.csv() 的默认选项)

请注意,在数据的 str 结构中,Air_WeightWater_Weight 是数字(缩写为 num)。这很好。我们可以继续线性模型:

fit <- lm(Water_Weight~Air_Weight, data=table1)

尝试以下操作:

GENDER <- c(1,1,1,1,1)
Air_Weight <- c(75.60, 70.70, NA, 95.00, 73.20)
Water_Weight <- c(NA, 3.60, 4.00, 4.30, 3.80)
Body_Fat <- c(14.17, 13.95, 8.98, 17.32, 11.50)
ID <- c(01, 02, 03, 04, 05)
data <- data.frame(GENDER, Air_Weight, Water_Weight, Body_Fat)
data

这给了我们以下信息:

       GENDER  Air_Weight   Water_Weight   Body_Fat
1      1       75.6          NA             14.17
2      1       70.7          3.6            13.95
3      1       NA            4.0            8.98
4      1       95.0          4.3            17.32
5      1       73.2          3.8            11.50

然后我们将其拟合到线性模型中:

fit <- lm(Water_Weight~Air_Weight, data=data)
fit

输出为:

lm(formula = Water_Weight ~ Air_Weight, data = data)

Coefficients:
(Intercept)   Air_Weight  
 1.7895       0.0265