[英]Plotting linear regression line of a calculation
我正在尝试为以下问题绘制线性回归线。 如果第一列是一个房间里的狗的数量,第二列代表每只狗可以抓取的食物量,那么当有 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))
由于这听起来像是家庭作业,我将向您展示如何仅使用 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 包(v0.2.1) 于 2019 年 6 月 28 日创建
听起来您想要每个房间 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.