执行线性回归时出错

时间:2016-05-03 12:27:02

标签: r linear-regression

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

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

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

这是我尝试过的代码,但出现了错误: -

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

This is the data screenshot

错误

**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 

2 个答案:

答案 0 :(得分:1)

您的数据结构存在一些问题,可能是基于您将其读入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)

答案 1 :(得分:1)

尝试以下方法:

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  
相关问题