绘制计算的线性回归线

时间:2019-06-28 20:00:17

标签: r plot linear-regression

我正在尝试为以下问题绘制线性回归线。如果第一列是一个房间里住的狗的数量,第二列表示每只狗可以抓的食物量,那么当分别有10只狗和15只狗时,每只狗可以估计的食物量是多少,在房间里?我需要编写一个函数来计算给定x向量的估计值y向量。用“ o”点画出实际值,用“ +”点画出估计值。您还需要绘制回归线。)

以下提示:

lmout <- lm (y ~ x)

intercept <- lmout[1]$coefficients[[1]]
constant <- lmout[1]$coefficients[[2]]

我不知道根据这个问题需要计算什么。如果给定的矩阵如下所示,我不明白需要什么:

  Number of dogs in a room Amount of food each dog can grab
1                        8                               12
2                       20                               15
3                       10                                2

该问题要求计算在每个房间分别有10只和15只狗的情况下,每只狗可获取的估计食物量是多少? 到目前为止,我正在绘制矩阵和回归线的值。

rownames = c("1","2","3") #Declaring row names
colnames = c("Number of dogs in a room", "Amount of food each dog can grab") #Declaring column names

v <- matrix(c(8,12,20,15,10,2), nrow = 3, byrow=TRUE, dimnames = list(rownames,colnames))

print(v) # Prints the matrix of the data

# Data in vector form
x <- c(8,20,10)
y <- c(12,15,2)

# calculate linear model
lmout <- lm (y ~ x)
# plot the data
plot(x,y, pch =19)
# plot linear regression line
abline(lmout, lty="solid", col="royalblue")

# Function
func <- function(lmout,x){

  intercept <- lmout[1]$coefficients[[1]]
  constant <- lmout[1]$coefficients[[2]]

  regline2 <- lm(intercept, constant) 
  abline(regline2, lty="solid", col="red")

}

print(func(lmout,x))

2 个答案:

答案 0 :(得分:1)

听起来您想要每个房间10和15条狗的food的预测值。您可以使用predict来做到这一点。首先,我将矩阵转换为数据框,以简化操作:

# Turn you matrix into a dataframe.
df <- data.frame(dogs = v[,1], food = v[,2])

然后我可以计算我的模型和基于该模型的预测:

# Compute the linear model.
lmout <- lm(food ~ dogs, df)

# Create a dataframe with new values of `dogs`.
df_new <- data.frame(dogs = c(10, 15))

# Use `predict` with your model and the new data.
df_new$food <- predict(lmout, newdata = df_new)

#### PREDICTIONS OUTPUT ####

  dogs      food
1   10  8.096774
2   15 11.040323

现在我可以用回归线绘制数据和新数据了。

plot(df$dogs, df$food, pch = 21)
abline(lmout, lty="solid", col="royalblue")
points(df_new$dogs, df_new$food, pch = 3, col = "red")

enter image description here

答案 1 :(得分:0)

由于这听起来像是作业,因此我将向您展示如何仅使用R中的内置函数来执行此操作。您必须构建自己的函数才能动态地执行此操作。如果您是老师希望您从头开始,请记住:

yhat = beta0 + beta1 * x # No LaTeX Support here?

dog_dat <- data.frame("dogs_room" = c(8, 20, 10), "food" = c(12, 15, 2))
dog.lm <- lm(dogs_room ~ food, data = dog_dat)

plot(dog_dat$food, dog_dat$dogs_room)
points(dog_dat$food, fitted.values(dog.lm), col = "red")
abline(dog.lm)

reprex package(v0.2.1)于2019-06-28创建