dplyr:使用 poly 函数生成多项式系数

dplyr: Using poly function to generate polynomial coefficients

我想将多项式系数附加到 data.frame,如下例所示:

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]
    )

不知道有没有这样简洁的方法

df1 %>%
  dplyr::mutate(poly(x = Y, degree = 3, raw = TRUE))

谢谢

不完全是您希望的方式,但足够接近了。我首先将 poly(矩阵)的输出转换为 data.frame,然后使用 !!! 拼接列(将 list/data.frame 的每个元素转换为它自己的争论)。 setNames 对于重命名列是可选的:

library(dplyr)

df1 %>%
  mutate(!!!as.data.frame(poly(x = .$Y, degree = 3, raw = TRUE))) %>%
  setNames(c("Y", "Linear", "Quadratic", "Cubic"))

结果:

    Y Linear Quadratic Cubic
1   4      4        16    64
2   4      4        16    64
3   4      4        16    64
4   4      4        16    64
5   4      4        16    64
6   8      8        64   512
7   8      8        64   512
8   8      8        64   512
9   8      8        64   512
10  8      8        64   512
11 16     16       256  4096
12 16     16       256  4096
13 16     16       256  4096
14 16     16       256  4096
15 16     16       256  4096
16 32     32      1024 32768
17 32     32      1024 32768
18 32     32      1024 32768
19 32     32      1024 32768
20 32     32      1024 32768
...

另一个选择,虽然我很喜欢@useR的解决方案:

df1 %>%
  left_join(data.frame(Y = unique(.$Y), poly(unique(.$Y), degree = 3, raw = TRUE)),
            by = c('Y' = 'Y')) %>% 
  setNames(c('Y', 'Linear', 'Quadratic', 'Cubic'))

    Y Linear Quadratic Cubic
1   4      4        16    64
2   4      4        16    64
3   4      4        16    64
4   4      4        16    64
5   4      4        16    64
6   8      8        64   512
7   8      8        64   512
8   8      8        64   512
9   8      8        64   512
10  8      8        64   512
11 16     16       256  4096
12 16     16       256  4096
13 16     16       256  4096
14 16     16       256  4096
15 16     16       256  4096
16 32     32      1024 32768
17 32     32      1024 32768
18 32     32      1024 32768
19 32     32      1024 32768
20 32     32      1024 32768