3

我想将多项式系数附加到 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))

谢谢

4

2 回答 2

8

不完全是您希望的方式,但足够接近。我首先将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
...
于 2018-08-14T15:40:10.463 回答
2

另一种选择,虽然我真的很喜欢@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
于 2018-08-14T15:49:44.980 回答