rstringloopssystemfit

R: Columnwise loop over string variables


my first R question that has not been discussed in any forum yet, apparently...Consider my fake dataset:

A<-matrix(c(1,2,3,4,5,2,3,4,5,6,3,4,5,6,7),5,3)    
a<-c(2,4,6,8,9)

I want to regress each column of A on a and perform systemfit to test some restrictions, e.g.:

system.1<-list(A[,1]~a,A[,2]~a,A[,3]~a)    
systemfit(system.1)

Now my problem is that my "real" matrix A has hundreds of columns. I'm struggling to create a list that systemfit accepts. I've come up with the following, not workable code:

varlist=NULL    
for (i in 1:3){varlist[i] <- paste("A[,",i,"] ~ a",sep="")}    
  models <- lapply(varlist, function(x){    
  systemfit(substitute(j, list(j = as.name(x))))    
})    

If you hit

substitute(j, list(j = as.name(varlist)))

you can see that the solution

`A[,1] ~ a`

contains `` signs which seem to be causing the trouble for systemfit, since it is not accepted as a formula. Hence the problem seems to be the columnwise looping, but I dont see any alternative for the dataset at hand...Any ideas?

Any help would be highly appreciated!

Thanks!


Solution

  • The idiomatic way to do this is to create a list of formulas which reference columns in a data frame, then pass the list and the data frame to systemfit(...).

    df    <- data.frame(a,A)  # data frame with columns a, X1, X2, X3, ...
    forms <- lapply(paste0(colnames(df)[-1],"~a"),as.formula)
    library(systemfit)
    systemfit(forms,data=df)
    # systemfit results 
    # method: OLS 
    #
    # Coefficients:
    # eq1_(Intercept)           eq1_a eq2_(Intercept)           eq2_a eq3_(Intercept)           eq3_a 
    #       -0.182927        0.548780        0.817073        0.548780        1.817073        0.548780