I want to append polynomial coefficient to data.frame as the example given below:
df1 <-
structure(list(
Y = c(4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 16, 16, 16,
16, 16, 32, 32, 32, 32, 32, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 16,
16, 16, 16, 16, 32, 32, 32, 32, 32, 4, 4, 4, 4, 4, 8, 8, 8, 8,
8, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32)),
class = "data.frame", row.names = c(NA, -60L))
library(tidyverse)
df1 %>%
dplyr::mutate(
Linear = poly(x = Y, degree = 3, raw = TRUE)[ ,1]
, Quadratic = poly(x = Y, degree = 3, raw = TRUE)[ ,2]
, Cubic = poly(x = Y, degree = 3, raw = TRUE)[ ,3]
)
I wonder if there is a concise method like this
df1 %>%
dplyr::mutate(poly(x = Y, degree = 3, raw = TRUE))
Thanks
Not exactly the way you were hoping, but close enough. I first convert the output of
poly
(a matrix) to a data.frame, then use!!!
to splice the columns (turning each element of a list/data.frame into it's own argument).setNames
is optional for renaming the columns:Result: