R 函数将数据帧剥离为单独的列多边形



我需要更新我的代码以使其更加动态。

我的数据帧有时可以包含 6 个变量,有时可以包含 9 个变量。我需要基于相关变量创建一个数据帧,其中包含所有不同的变量和相应的二阶变量。

我的代码曾经看起来像这样

df3 <- data.frame(poly(test$hub, test$vacations, test$slot, test$income, test$market_size, test$average_distance_m, degree = 2, raw = TRUE))
df6 <- data.frame(poly(test$hub, test$vacations, test$slot, test$income, test$market_size, test$average_distance_m, test$noise1, test$noise2, test$noise3, degree = 2, raw = TRUE))

我想知道是否有任何方法可以使它更具活力。 我试过了

df <- data.frame(poly(test, degree = 2, raw = TRUE))

测试会更新的地方,但我在 FUN(X, Y, ...( 中不断收到错误:二进制运算符的非数字参数

如果您将数据转换为矩阵,那么您的最后一次尝试将起作用。

例如

# typing all variables in manually
original = with(mtcars, poly(mpg, cyl, disp, hp, drat, wt, degree=2, raw=TRUE))
#OR
# convert dataframe to matrix and apply poly (lazily using indices instead of names)
using_matrix = poly(as.matrix(mtcars[1:6]), degree=2, raw=TRUE)
all.equal(original, using_matrix, check.attributes=FALSE)
# TRUE

你需要使用do.call

my_funct = function(dat) do.call(poly,c(unname(dat),raw=TRUE,degree=2))
(df_2vars <- my_funct(iris[1:2]))
(df_4vars <- my_funct(iris[1:4]))

最新更新