R中的多项式特征展开

sir*_*len 2 statistics r

我想对数据帧进行多项式特征展开-例如,使用(x1,x2,x3)的df的二次展开应使用(x1,x2,x3,x1 ^ 2,x2 ^ 2,x3 ^ 2,x1x2,x1x3,x2x3)。我目前正在使用,poly(df$x1, df$x2, df$x3, degree=2, raw=T)但是如果我有大量的列,这需要不必要的输入。(并且poly(df[,1:20], degree=2, raw=T)不起作用。)执行此操作的最佳方法是什么?

编辑:我有太多列polyvector is too large错误)。得到它以一个简单的for循环工作:

polyexp = function(df){
  df.polyexp = df
  colnames = colnames(df)
  for (i in 1:ncol(df)){
    for (j in i:ncol(df)){
      colnames = c(colnames, paste0(names(df)[i],'.',names(df)[j]))
      df.polyexp = cbind(df.polyexp, df[,i]*df[,j])
    }
  }
  names(df.polyexp) = colnames
  return(df.polyexp)
}
Run Code Online (Sandbox Code Playgroud)

只需添加其他循环即可计算高阶项。

jos*_*ber 5

您可以使用do.call

do.call(poly, c(lapply(1:20, function(x) dat[,x]), degree=2, raw=T))
Run Code Online (Sandbox Code Playgroud)

基本上do.call将要调用的函数(poly在您的情况下)作为第一个参数,并将列表作为第二个参数。然后,将此列表的每个元素作为参数传递给您的函数。在这里,我们创建了一个列表,其中包含您要处理的所有列(我曾经lapply在没有太多输入的情况下获取该列表),然后是要传递的两个其他参数。

要查看它在一个简单示例中的工作:

dat <- data.frame(x=1:5, y=1:5, z=2:6)
do.call(poly, c(lapply(1:3, function(x) dat[,x]), degree=2, raw=T))
#      1.0.0 2.0.0 0.1.0 1.1.0 0.2.0 0.0.1 1.0.1 0.1.1 0.0.2
# [1,]     1     1     1     1     1     2     2     2     4
# [2,]     2     4     2     4     4     3     6     6     9
# [3,]     3     9     3     9     9     4    12    12    16
# [4,]     4    16     4    16    16     5    20    20    25
# [5,]     5    25     5    25    25     6    30    30    36
# attr(,"degree")
# [1] 1 2 1 2 2 1 2 2 2
Run Code Online (Sandbox Code Playgroud)