I need to compare the output of a third-degree polynomial matrix between Python and R. The values seem to match but the order is off. Is there a way to order the poly output in R to match that of Python?
Example data: x = 2,3,4,5,6
Python Code:
X = np.vstack([2,3,4,5,6]).T
poly = PolynomialFeatures(degree=3)
X_ = poly.fit_transform(X)
Python Output:
array([[ 1., 2., 3., 4., 5., 6., 4., 6., 8., 10., 12., 9., 12., 15., 18., 16., 20., 24., 25., 30., 36., 8., 12., 16., 20., 24., 18., 24., 30., 36., 32., 40., 48., 50., 60., 72., 27., 36., 45., 54., 48., 60., 72., 75., 90., 108., 64., 80., 96., 100., 120., 144., 125., 150., 180., 216.]])
R Code:
x <- t(c(2, 3, 4, 5, 6))
dx <- c(1, as.numeric(poly(x, degree = 3, raw=TRUE)))
R Output:
[1] 1 2 4 8 3 6 12 9 18 27 4 8 16 12
[15] 24 36 16 32 48 64 5 10 20 15 30 45 20 40
[29] 60 80 25 50 75 100 125 6 12 24 18 36 54 24
[43] 48 72 96 30 60 90 120 150 36 72 108 144 180 216
This seems to do it:
x <- t(c(2, 3, 4, 5, 6))
p <- poly(x, degree = 3, raw=TRUE)
c(1, p[order(-attr(p, "degree"), colnames(p), decreasing = TRUE)])
#[1] 1 2 3 4 5 6 4 6 8 10 12 9 12 15 18 16 20 24 25 30 36 8 12 16 20 24 18 24 30 36 32
#[32] 40 48 50 60 72 27 36 45 54 48 60 72 75 90 108 64 80 96 100 120 144 125 150 180 216