I am trying to write a for-loop in r that loops over data I have starting in 1970. I want to loop over the years themselves so that I will have an iteration for each year in the data and store the data (vote shares, incumbency status, etc) in a vector.
Obviously, since my data starts in 1970 I don’t want values for years < 1970 however, the script below is producing a vector with 0’s for in locations 1-16, NA in locations 17-1969 and then what I believe is the intended statistic in even years 1970-2000 and NA in in odd years. How do I get this to return just the values I want (even years 1970-2000?) And what is going on with the 0 values in positions 1-16?
incumb.data is data frame with the vote shares, incumbency status, election outcomes by year and state.
\script:
J<-seq(1970, 2000,2)
inc.fx1<-vector(length=length(J))
year.df1<-vector(length=length(J))
for (j in 1970:J){
state.hold<-incumb.data[StateNumb3==26,]
yr.hold<-state.hold[state.hold$V6==j,]
St28.df<-data.frame(year=yr.hold$V6,
v_1=yr.hold$v_1, v_2=yr.hold$v_2,
I1=yr.hold$I1, I2=yr.hold$I2,
P2=yr.hold$P2)
St28.lm<-lm(v_2~v_1+I2+P2, data=St28.df)
inc.fx1[j]<-coef(St28.lm)[3]
year.df1[j]<-St28.df$year
}
\end script
So I want the inc.fx1 to hold the calculated statistic for the even years 1970-2000.Thanks for any help.
BG
J is a vector, and you can iterate over it directly.
Replace this (which should give a warning):
With this: