You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中针对自有数据集拟合线性模型?

Fitting a Linear Model in R with Your Specific Dataset

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 Ay using Ty and year as predictors:
    fit_ay <- lm(Ay ~ Ty + year, data = mydata)
    
  • If you want to predict Ty using Ay and year as predictors:
    fit_ty <- lm(Ty ~ Ay + year, data = mydata)
    
  • If you only want to use one predictor (e.g., year to predict Ay):
    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 Ay changes with a 1-unit increase in Ty or year)
  • R-squared value (how much variance in Ay is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:20:10