计算model_matrix中所有可能的交互

问题描述 投票:0回答:1

我正在使用波动数量的变量来模拟数据。作为情况的一部分,我需要计算具有所有可能组合的模型矩阵。有关示例,请参见以下代表。通过将公式指定为~ .*.,我可以获得所有两个交互。但是,此特定数据集有3个变量(ndim <- 3)。通过将公式指定为~ .^3,我可以获得所有的双向和三向交互。问题是我需要计算4个以上的变量,所以我希望能够概括这一点。我已经尝试将公式指定为~ .^ndim,但这会引发错误。

有没有办法用变量定义公式中的幂?

library(tidyverse)
library(mvtnorm)
library(modelr)

ndim <- 3

data <- rmvnorm(100, mean = rep(0, ndim)) %>%
  as_tibble(.name_repair = ~ paste0("dim_", seq_len(ndim)))

model_matrix(data, ~ .*.)
#> # A tibble: 100 x 7
#>    `(Intercept)`  dim_1   dim_2    dim_3 `dim_1:dim_2` `dim_1:dim_3`
#>            <dbl>  <dbl>   <dbl>    <dbl>         <dbl>         <dbl>
#>  1             1 -0.775  0.214   0.111         -0.166       -0.0857 
#>  2             1  1.25  -0.0636  1.40          -0.0794       1.75   
#>  3             1  1.07  -0.361   0.976         -0.384        1.04   
#>  4             1  2.08   0.381   0.593          0.793        1.24   
#>  5             1 -0.197  0.382  -0.257         -0.0753       0.0506 
#>  6             1  0.266 -1.82    0.00411       -0.485        0.00109
#>  7             1  3.09   2.57   -0.612          7.96        -1.89   
#>  8             1  2.03   0.247   0.112          0.501        0.226  
#>  9             1 -0.397  0.204   1.55          -0.0810      -0.614  
#> 10             1  0.597  0.335   0.533          0.200        0.319  
#> # … with 90 more rows, and 1 more variable: `dim_2:dim_3` <dbl>

model_matrix(data, ~ .^3)
#> # A tibble: 100 x 8
#>    `(Intercept)`  dim_1   dim_2    dim_3 `dim_1:dim_2` `dim_1:dim_3`
#>            <dbl>  <dbl>   <dbl>    <dbl>         <dbl>         <dbl>
#>  1             1 -0.775  0.214   0.111         -0.166       -0.0857 
#>  2             1  1.25  -0.0636  1.40          -0.0794       1.75   
#>  3             1  1.07  -0.361   0.976         -0.384        1.04   
#>  4             1  2.08   0.381   0.593          0.793        1.24   
#>  5             1 -0.197  0.382  -0.257         -0.0753       0.0506 
#>  6             1  0.266 -1.82    0.00411       -0.485        0.00109
#>  7             1  3.09   2.57   -0.612          7.96        -1.89   
#>  8             1  2.03   0.247   0.112          0.501        0.226  
#>  9             1 -0.397  0.204   1.55          -0.0810      -0.614  
#> 10             1  0.597  0.335   0.533          0.200        0.319  
#> # … with 90 more rows, and 2 more variables: `dim_2:dim_3` <dbl>,
#> #   `dim_1:dim_2:dim_3` <dbl>

model_matrix(data, ~.^ndim)
#> Error in terms.formula(object, data = data): invalid power in formula

reprex package创建于2019-02-15(v0.2.1)

r lm modelr
1个回答
1
投票

你可以在as.formula中使用pastemodel_matrix

model_matrix(data, as.formula(paste0("~ .^", ndim)))
© www.soinside.com 2019 - 2024. All rights reserved.