使用if语句在R中进行线性回归 [英] Linear regression in R with if statement
本文介绍了使用if语句在R中进行线性回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个虚拟变量黑色
其中黑色== 0
是白色而黑色== 1
是黑色。我试图仅为 black == 1
类别拟合线性模型 lm
,但是运行以下代码给出我不正确的系数。在R中是否有办法使用 if
语句运行模型,类似于Stata?
I have a dummy variable black
where black==0
is White and black==1
is Black. I am trying to fit a linear model lm
for the black==1
category only, however running the code below gives me the incorrect coefficients. Is there a way in R to run a model with the if
statement, similar to Stata?
library(foreign)
df<-read.dta("hw4.dta")
attach(df)
black[black==0]<-NA
model3<-lm(rent~I(income^2)+income+black)
推荐答案
为什么不在运行模型之前对数据进行子集化?我个人更喜欢使用数据框而不是单独的向量,这将使子集更容易。
Why not subset the data before running the model? I personally prefer using a dataframe rather than separate vectors which will make the subsetting easier.
df <- data.frame(rent, income, black)
然后对数据帧进行子集化,o创建另一个
Then subset the dataframe, o create another one
df <- df[df$black==1,]
并运行模型
model3 <- lm(rent ~ I(income^2) , data=df)
这篇关于使用if语句在R中进行线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文