I';我不明白为什么图上的线条不是';t出现在R
这是我的代码,在我尝试创建一行之前,一切都在顺利运行 在情节中。它没有给我任何错误,只是没有显示I';我不明白为什么图上的线条不是';t出现在R,r,statistics,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) #Cr
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)
我看不出有什么问题,为什么R不显示我的台词 切勿使用
附加尤其是当您还使用使用非标准求值(采用不带引号的列名)的函数(如subset
)时,请不要使用attach
您将age
本身定义为一个向量,而不是tipsy
的一列,因此它也不会是sub
的一列。(我还没有运行您的代码,但我非常肯定这一点。)
您的调试策略应该是一次运行每一行,并查看控制台中的内容(或至少查看其头()
)。我想,如果你这样做了,你会注意到sub1
和sub2
没有age
列。你可以做很多事情来缩小问题的范围。与其使用50行代码来生成sub1
和sub2
,不如只给我们dput(head(sub1))
并询问为什么绘图不起作用——或者如果缺少sub1
列,请回顾您认为应该创建这些列的位置。我看到您已经注释掉了比率1我完全同意rawr。R代码乱七八糟,我们给你的任何确切答复都是猜测。也就是说,您是否尝试过在绘图函数中使用type=“l”
强制它使用线条?我有一种感觉,您对lines()
的调用正在删除您之前对plot()
@TimBiegeleisenplot()
的调用,然后是lines()
,这是非常常见的,不是问题。如果有数据,绘图代码应该可以正常工作。这使得OP没有找出问题是在数据准备还是在绘图中太糟糕了。
> 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