gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:46:49 26 4
gpt4 key购买 nike

我想将多项式系数附加到 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.框架到它自己的论点)。 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
...

关于r - dplyr:使用 poly 函数生成多项式系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com