【发布时间】:2019-06-29 04:52:24
【问题描述】:
我正在尝试为以下问题绘制线性回归线。如果第一列是住在一个房间里的狗的数量,第二列代表每只狗可以抓取的食物量,那么当有 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))
【问题讨论】:
-
也许您想尝试查看
str(lmout),它向您展示了lm输出的结构,并且可能已经包含一些您感兴趣的值。也许lmout$fitted.values对你有特别的兴趣?
标签: r plot linear-regression