calling a function for all elements of a vector

81 Views Asked by At

Hi I am trying to execute a Linear Regression using a few separate models and a few separate seeds.

Currently I have the following which works but doesn't seem very R like

library(RWeka)
library(datasets)
library(foreach)

m0 <- LinearRegression(mpg~.,data=mtcars,control=Weka_control(S=0))
m1 <- LinearRegression(mpg~.,data=mtcars,control=Weka_control(S=1))
m2 <- LinearRegression(mpg~.,data=mtcars,control=Weka_control(S=2))

models <- list(m0,m1,m2)

seeds <- c(1:10)

foreach(m = models) %:%
  foreach(x = c(1:10)) %do%
    evaluate_Weka_classifier(m,numFolds = 10,seed = seed)

So is there are more R like way to do this and if not, does anyone know how to accomplish what I am trying to do here with looping over the different models?

R version 3.2.0 (2015-04-16)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

EDIT: I figured this iterating over the models part out and updated the post accordingly. This still leaves the question is there a better way to do this than foreach (which doesn't seem very r like)

1

There are 1 best solutions below

0
On

I'm not familiar with the details of evaluate_Weka_classifier, but generally it seems you could do this, which will return a list of lists. Not necessarily better than foreach, but perhaps more "R-ish" since it uses a base function (for whatever that's worth)

lapply(models, function(m) {
  lapply(1:10, function(seed) {
    evaluate_Weka_classifier(m, numFolds = 10, seed = seed)
  })
})