This isn't completely general, but solves your specific problem and should be adaptable.
I modified the example slightly (esp. using raw=TRUE
):
set.seed(101)
g1=sin((1:1000)/60/pi)+runif(1000)^0.3
g2=cos((1:1000)/90/pi)+runif(1000)^0.3
gl=g1-g2+(g1*g2)+rnorm(10)/2
mymodel <- lm(gl~poly(g1,3,raw=TRUE)+
poly(g2,3,raw=TRUE)+poly(g1*g2,3,raw=TRUE))
cc <- coef(mymodel)
pfun <- function(x,v) {
paste(x,paste(v,seq(length(x)),sep="^"),sep="*",
collapse="+")
}
pfun(1:3,"x")
## [1] "1*x^1+2*x^2+3*x^3"
strwrap(paste(c(cc[1],pfun(cc[2:4],"g1"),pfun(cc[5:7],"g2"),
pfun(cc[8:10],"(g1*g2)")),collapse="+ "))
## [1] "-0.0503143118026683+"
## [2] "1.04495433152782*g1^1+-0.212330489393473*g1^2+0.0378835573948955*g1^3+"
## [3] "-1.0979460962483*g2^1+-0.240393392043387*g2^2+0.0724299094173384*g2^3+"
## [4] "1.4803777033041*(g1*g2)^1+-0.0638557942781872*(g1*g2)^2+-0.00209039494007401*(g1*g2)^3"