[R] dataframe in loop

Muting Zhang MT208071 at dal.ca
Tue Mar 30 19:30:50 CEST 2010


hello all:

I would like to thank those who helped me out of the string  
problem..but now I got another problem.
I used R to query from SQL and got a list of crsp_fundno of G-style mutual
funds which is still alive. I use the following codes and got what I want:

library(RODBC)
channel<-odbcConnect("CRSPFUND")
g.crspfundno<-sqlQuery(channel,"select crsp_fundno from Fund_style where
wbrger_obj_cd = 'G'order by crsp_fundno")
g.crspfundno (got crsp_fundno of G-style fund from Fund_style table)
y.crspfundno<-sqlQuery(channel,"select crsp_fundno from Fund_hdr where  
dead_flag
= 'N'and end_dt=20091231 order by crsp_fundno")
y.crspfundno (got crsp_fundno of still alive fund from Fund_hdr table)
g$key<-paste(g.crspfundno$crsp_fundno)
y$key<-paste(y.crspfundno$crsp_fundno)
v.fundno<-intersect(g$key,y$key) (using intersect to get crsp_fundno  
of G-style
mutual funds which is still alive.)
v.fundno

What i need to do next is using the v.fundno I got to query from another table
"Monthly_return" to get the mret coresponding to every v.fundno.
I have only a basic idea of the code:
for (i in 1:length(v.fundno)){
gmret<-sqlQuery(channel,paste("select mret from Monthly_returns where  
crsp_fundno =",test[i],'and caldt > 19900630 order by caldt'))
}

The loop doesn't work:( I realize it might be the problem that I didnt  
define the dataframe, but my limited knowledge cant help me find out  
how..

I will give you guys a example of my data:
head(v.fundno)
test<-head(v.fundno)
test
[1] "2899" "2903" "2960" "3094" "3095" "3211"
If I dont do the loop and query for one fund say 2899,
gmret.2899<-sqlQuery(channel,"select caldt, mret from Monthly_returns  
where crsp_fundno = 2899 and caldt > 19900630 order by caldt")
gmret.2899
It will give me what I want:
  sample2899<-head(gmret.2899)
  sample2899
      caldt         mret
1 19900731  0.014204546
2 19900831 -0.050420168
3 19900928 -0.039823009
4 19901031  0.006144393
5 19901130  0.054961832
6 19901231  0.019632639

Can anybody help me with the loop?
Thanks a lot

Muting



More information about the R-help mailing list