我不明白为什么情节上的线条没有出现在R中

时间:2015-02-19 06:24:27

标签: r statistics

这是我的代码,一切都运行顺利,直到我尝试创建一行 在情节中。它没有给我任何错误,只是没有出现!

setwd("~/RESEARCH/") 
NHISdata <- read.csv("NHIS Data.csv", header=TRUE) 
attach(NHISdata) 
age = 21 + days_21/365 
#Create a variable centered at 0, for pre and post 

z=ifelse(age>=21,1,0) 
#Create a polynomial in age 

agec=age-21 
agec_sq=agec^2 
agec_cu=agec^3 
#Interact with the post variable 
agec_post=agec*z 
agec_sq_post=agec_sq*z 
agec_cu_post=agec_cu*z 

reg1<- lm(drinks_alcohol ~ z + agec + agec_post) 
reg2<- lm(drinks_alcohol ~ z + agec + agec_sq + agec_post + agec_sq_post) 
reg3<- lm(drinks_alcohol ~ z + agec + agec_sq+ agec_cu + agec_post + 
agec_sq_post + agec_cu_post) 

#z will give us the jump at 21 
summary(reg1) 
summary(reg2) 
summary(reg3) 

pred_rate_linear <- predict(reg1) 
pred_rate_quad <- predict(reg2) 
pred_rate_cubic <- predict(reg3) 

#rate1 <- 
cbind(NHISdata,z,agec,agec_sq,agec_cu,agec_post,agec_sq_post,agec_cu_post,pred_rate_linear,pred_rate_quad,pred_rate_cubic)
#attach(rate1) 
bin7=floor(days_21/7) 
bin14=floor(days_21/14) 
bin30=floor(days_21/30) 
bin100=floor(days_21/100) 
tipsy = data.frame(cbind(days_21,drinks_alcohol,bin7,bin14,bin30,bin100)) 
tipsy = aggregate(NHISdata,by=list(bin30),FUN=mean) 
attach(tipsy) 
par(mfrow=c(2,2), oma=c(0,0,2,0)) 
age = 21 + days_21/365 
plot(x=age, y=drinks_alcohol, xlim=c(19,23), ylim=c(.4,.75), xlab='Age', 
ylab='Drinking Rate', cex = 0.75) 
title(main='Linear Regression') 
sub1 <- subset(tipsy, age>=21) 
sub2 <- subset(tipsy, age<=21) 
lines(sub1$age, sub1$pred_rate_linear) 
lines(sub2$age, sub2$pred_rate_linear) 
summary(age) 
summary(pred_rate_linear) 

plot(x=age, y=drinks_alcohol, xlim=c(19,23), ylim=c(.4,.75), xlab='Age', 
ylab='Drinking Rate', cex = 0.75) 
title(main='W/ Linear Regression Line') 
sub1 <- subset(rate1, age>=21) 
sub2 <- subset(rate1, age<=21) 
lines(sub1$age, sub1$pred_rate_quad, col="red", lwd=3) 
lines(sub2$age, sub2$pred_rate_quad, col="red", lwd=3) 

这是csv文件的链接供您试用。 http://speedy.sh/BdmP5/NHIS-Data.csv

年龄摘要和pred_rate_quad是

> summary(age) 
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  17.70   20.87   24.00   24.00   27.12   30.85 
> summary(pred_rate_linear) 
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 0.3096  0.6599  0.6631  0.6243  0.6665  0.6701 

我没有看到问题,为什么R不显示我的线条?

1 个答案:

答案 0 :(得分:0)

永远不要使用attach特别是当您还使用使用非标准评估的subset等函数时,从不使用附加(使用不带引号的列名称)。

您可以将age定义为矢量,而不是tipsy的列,因此它也不会成为sub的列。 (我没有运行你的代码,但我很确定这一点。)

您的调试策略应该是一次一个地运行每一行,并在控制台中查看它是什么(或至少在其head()处)。我想,如果您这样做了,您会注意到sub1sub2没有age列。您可以做很多事情来缩小问题所在。不应该使用50行代码来生成sub1sub2,而应该只是给我们dput(head(sub1))并询问为什么情节不起作用---或者{ {1}}缺少列回溯到您认为应该创建它们的位置。

相关问题