Extracting data used to make a smooth plot in mgcv

后端 未结 3 1388
我在风中等你
我在风中等你 2020-12-10 03:11

This thread from a couple of years ago describes how to extract data used to plot the smooth components of a fitted gam model. It works, but only when there is one smooth v

3条回答
  •  无人及你
    2020-12-10 03:38

    Gavin gave a great answer, but I wanted to provide one in terms of the original referenced post (as I just spent a good amount of time figuring out how that worked :).

    I used the code directly from https://stats.stackexchange.com/questions/7795/how-to-obtain-the-values-used-in-plot-gam-in-mgcv and also found that I only got the last model returned. The reason for that is because of where the trace code snippet is being placed in the mgcv::plot.gam function. You need to make sure that the code is placed inside a for loop that iterates over m, and you control that by the at argument.

    The following trace worked great for my version of mgcv:::plot.gam

    plotData <<- list()
    trace(mgcv:::plot.gam, at=list(c(26,3,4,3)), 
    quote({
           plotData[[i]] <<- pd[[i]]
      })
    )
    

    It inserts the trace call right after this chunk in the mgcv:::plot.gam function:

    if (m > 0) 
        for (i in 1:m) if (pd[[i]]$plot.me && (is.null(select) || 
            i == select)) {
    

    and now the elements of plotData will correspond to the different variables plotted. Two functions I found very helpful for figuring out the right place to insert this trace call were

    edit(mgcv:::plot.gam)
    as.list(body(mgcv::::plot.gam))
    

提交回复
热议问题