2
$\begingroup$

I have a dataframe that I would like to split into subsets and apply a GAM to each one. Ultimately I'd like to output a set of predictions to one large dataframe.

So far the approach I have tried to take:

  • Create function to build the model
  • Subset data into list of dataframes
  • Use lapply to turn list of dataframes into list of models

Is this the right approach or is there a better way?

# Function to create generalised additive model then create predictions
gam.function <- function(x)  {

  gam.x <- gam(x$switch ~ s(x$input_1) + s(x$input_2),   data=x) #%>%

  #predict(gam.x, newdata = data.frame(input_1 = 3500, input_2 = 13500))

}

# Create a list of data frames for position
position.split <- split(switch,switch$position)

# Return a list of models
model.list <- lapply(position.split, FUN=gam.function) 

An error is returned:

> model.list <- lapply(position.split, FUN=gam.function)
Error in gam(x$switch ~ s(x$input_1) + s(x$input_2),  : 
  Model has more coefficients than data

I know this error seems very clear but I'm struggling to interpret as I can successfully run one subset at a time without lapply.

$\endgroup$
2
  • 1
    $\begingroup$ test lapply(position.split, nrow) $\endgroup$
    – jogo
    Commented Nov 3, 2015 at 9:41
  • $\begingroup$ Ah brilliant, thanks jogo, one of the dataframes just had 1 row. Apologies. $\endgroup$
    – frankma
    Commented Nov 3, 2015 at 9:52

1 Answer 1

1
$\begingroup$

Your function could be:

gam.function <- function(x)  {
  if (nrow(x) < 3) return(" nrow() to small ")
  gam.x <- gam(switch ~ s(input_1) + s(input_2), data=x) #%>%  
  #predict(gam.x, newdata = data.frame(input_1 = 3500, gas_kwh = input_2))  
}
$\endgroup$
3
  • $\begingroup$ Good shout, thanks. Do you know why the predict statement fails with the error: "not all required variables have been supplied in newdata!" Seems like another obvious one... $\endgroup$
    – frankma
    Commented Nov 3, 2015 at 10:15
  • $\begingroup$ yes, you wrote gas_kwh = input_2but you want to wrote input_2 = gas_kwh or something other. $\endgroup$
    – jogo
    Commented Nov 3, 2015 at 10:18
  • $\begingroup$ Sorry that was me editing it to make it generic and making a mistake, it's not actually that unfortunately. Both inputs are numeric. See my correction above. $\endgroup$
    – frankma
    Commented Nov 3, 2015 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.