如何在R语言中针对自有数据集拟合线性模型?
Hey there! Let's break down exactly how to fit your linear model using your dataset. I'll walk you through every step, from setting up your data to running the model and checking results.
Step 1: Create Your Dataset in R
First, we need to get your provided data into a data frame that R can work with. Here's the code to do that:
# Create the dataset mydata <- data.frame( Ay = c(20, 48, 35), Ty = c(11, 27, 58), year = c(2009, 2010, 2011) ) # Verify the data was created correctly print(mydata)
Running print(mydata) will show you the table matches your original data, so you can confirm everything's set up right.
Step 2: Fit Your Linear Model
The general lm() syntax you found (fit <- lm(y ~ x1 + x2, data=mydata)) translates directly to your dataset—you just need to replace y, x1, and x2 with your actual column names.
Let's cover common scenarios based on what you want to predict:
- If you want to predict
AyusingTyandyearas predictors:fit_ay <- lm(Ay ~ Ty + year, data = mydata) - If you want to predict
TyusingAyandyearas predictors:fit_ty <- lm(Ty ~ Ay + year, data = mydata) - If you only want to use one predictor (e.g.,
yearto predictAy):fit_ay_year <- lm(Ay ~ year, data = mydata)
Each of these lines creates a linear model object stored in variables like fit_ay—you can name them whatever makes sense to you.
Step 3: Examine the Model Results
Once you've fit the model, use the summary() function to get detailed statistics about how well the model performs, coefficient estimates, and more:
# For the Ay prediction model summary(fit_ay)
This output will show you things like:
- Coefficients for each predictor (how much
Aychanges with a 1-unit increase inTyoryear) - R-squared value (how much variance in
Ayis explained by the predictors) - p-values (whether each predictor is statistically significant)
A Quick Note on Your Small Dataset
Keep in mind that your dataset only has 3 observations—this is a very small sample size. Linear models work best with more data, so the results here should be taken as illustrative rather than statistically robust. If you can get more data points, your model will be much more reliable!
内容的提问来源于stack exchange,提问作者PitterJe

