[R] outer() or some other function for regression prediction with 2 IVs
Michael Weylandt
michael.weylandt at gmail.com
Tue Jul 10 05:30:58 CEST 2012
Your problem is the sum() call -- it's not vectorized (in the regular sense) so it breaks some of the internal assumptions of outer().
Easiest way is probably to do matrix multiplication (%*%) directly here
Michael
On Jul 9, 2012, at 10:19 PM, Joseph Clark <joeclark77 at hotmail.com> wrote:
>
> Hi there, I'm trying to prep some data for a persp() surface plot
>
> representing the predictions from a regression with two inddependent
>
> variables. The regression model "m3" has an intercept, 2 linear terms,
>
> and 2 squared terms. The coefficients are given by coef(m3).
>
>
>
> My approach to generating the predictions for a range of each of my IVs,
>
> "s" and "d" was to use outer() like so:
>
>
>
> predxn <- function(s,d) { sum( coef(m3) * c(1,s,s^2,d,d^2) ) }
> z <- outer(s_vector,d_vector,predxn)
>
>
>
> I can't see what's wrong with this. For each value of s_vector and d_vector,
>
> it should multiply each coefficient by its term and give me a nice
>
> two-dimensional array "z" containing the predictions.
>
>
>
> The problem is that the c() vector ends up with 1601 elements instead of 5.
>
> There are 20 items each in s_vector and d_vector so it looks like each variable
>
> in my function is using the whole "z" array of s's and d's rather than being
>
> calculated for each combination of values one at a time.
>
>
>
> So, am I using outer() wrong? Or did I write my function badly?
>
> Or is there a better way to plot a 3d surface plot of my regression model?
>
>
>
>
>
>
> // joseph w. clark , phd candidate
> \\ usc marshall school of business
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list