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

如何在R语言lm()模型中移除特定分类预测变量State2?

How to Remove the State2 Level from Your Linear Model in R

Got it, let's walk through this step by step. When you include the factor variable State in your lm() call, R automatically creates k-1 dummy variables (where k is the number of factor levels) using the first level ("1" in your case) as the reference. That's why you see State2 and State3 in your model summary.

If you want to remove State2 from the model, here are three common approaches depending on your exact goal:

Option 1: Keep all observations, exclude the State2 dummy variable

If you want to retain all rows in your dataset but don't want the model to account for the difference between State=2 and the reference level (State=1), you can explicitly subtract State2 from your model formula:

regressor <- lm(Profit~R.D.Spend+Administration+Marketing.Spend+State - State2, data=dataset)

After running this, summary(regressor) will only show the State3 term for the State variable—State=2 will be treated the same as State=1 in the model.

Option 2: Remove all State=2 observations from the dataset

If you don't want to use any rows where State is "2" to fit the model at all, filter your dataset first:

# Filter out rows where State equals "2"
dataset_filtered <- subset(dataset, State != "2")
# Fit the model on the filtered data
regressor <- lm(Profit~R.D.Spend+Administration+Marketing.Spend+State, data=dataset_filtered)

Now the State variable only has levels "1" and "3", so the model will only generate a State3 dummy variable, and State2 won't appear in the output at all.

Option 3: Make State2 the reference level (so it doesn't show up in the summary)

If you just want State2 to be the baseline category (instead of State=1), re-level the factor before fitting the model:

# Set "2" as the reference level for State
dataset$State <- relevel(dataset$State, ref = "2")
# Refit the linear model
regressor <- lm(Profit~R.D.Spend+Administration+Marketing.Spend+State, data=dataset)

This time, the model summary will show State1 and State3 as the dummy variables—State2 is now the reference, so it won't appear as a separate term in the output.

Choose the method that matches what you're trying to accomplish: whether you want to keep State=2 observations but ignore their unique effect, exclude those rows entirely, or shift the baseline category.

内容的提问来源于stack exchange,提问作者user9093127

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:14:52