Reputation: 11
I made loop code for linear regression by two subgroups combination and for two dependent variable. But it doesn't work with error. Is there someone can fix my code?
each_lm <-data.frame(matrix(nrow=1, ncol=10))
names(each_lm)=c("col1", "col2", "col3", "Estimate", " Std. Error", " z value", " pValue", "2.5%", "97.5%","r^2")
e=1
for (i in c("sbp","dbp")) {
for (j in c("1","2","3","4","5")) {
for (k in c("2002","2005","2008","2011","2014","2017")){
form <- formula(paste0(i,"~bmi"))
result <- lm(form, data=subset(bp, gr_bmi==j & year==k)
each_lm[e,1]<-i
each_lm[e,2]<-j
each_lm[e,3]<-k
each_lm[e,4]<-round(coef(summary(result))[2,1],3)
each_lm[e,5]<-round(coef(summary(result))[2,2],3)
each_lm[e,6]<-round(coef(summary(result))[2,3],3)
each_lm[e,7]<-round(coef(summary(result))[2,4],3)
each_lm[e,8]<-round(confint(result)[2,1],2)
each_lm[e,9]<-round(confint(result)[2,2],2)
each_lm[e,10]<-round(summary(result)$r.squared, 3)
e<-e+1
}
}
}
write.xlsx(each_lm, "c:/R/sbp_bmi/Table4_2.xlsx")
Error message:
Error: unexpected symbol in:
" result <- lm(form, data=subset(bp, gr_bmi==j & year==k)
each_lm"
Error: object 'k' not found
Error in round(summary(result)$r.squared, 3) :
non-numeric argument to mathematical function
Error: unexpected '}' in " }"
Error: unexpected '}' in " }"
Error: unexpected '}' in "}"
Upvotes: 0
Views: 102
Reputation: 1379
The error is that one of your functions is not closed properly. In the line:
result <- lm(form, data=subset(bp, gr_bmi==j & year==k)
There is only 1 closing bracket, whereas there should be 2, because you are callin 2 functions.
Replacing it with this will fix it
result <- lm(form, data=subset(bp, gr_bmi==j & year==k))
Upvotes: 2