Model matrix in R

42 Views Asked by At

I have this design in R (generated with

gen_design() 

from skpr package

X1
<dbl>
X2
<dbl>
X3
<dbl>
1   1   15  1   
2   0   10  1   
3   1   10  0   
4   1   10  1   
5   1   16  0   
6   0   16  1   
7   1   15  1   
8   0   17  0   
9   0   10  1   
10  0   10  0

with model.matrix attribute

$model.matrix
      (Intercept) X1         X2 X3
 [1,]           1  1  0.4285714  1
 [2,]           1 -1 -1.0000000  1
 [3,]           1  1 -1.0000000 -1
 [4,]           1  1 -1.0000000  1
 [5,]           1  1  0.7142857 -1
 [6,]           1 -1  0.7142857  1
 [7,]           1  1  0.4285714  1
 [8,]           1 -1  1.0000000 -1
 [9,]           1 -1 -1.0000000  1
[10,]           1 -1 -1.0000000 -1
[11,]           1 -1  1.0000000 -1
[12,]           1  1 -1.0000000 -1
[13,]           1 -1 -1.0000000 -1
[14,]           1  1  0.7142857 -1
[15,]           1 -1  0.7142857  1
[16,]           1  1 -1.0000000  1

My variable X1 is between 0 and 1 with 11 levels, X2 is between 10 and 20 with 11 levels, X3 is equal to x1. So this model matrix takes as -1 and 1 the extreme values (0/1, 10/20, 0/1) and i suppose it normalizes the values.

How can i get the same output of the model matrix with a design as

X1
<dbl>
X2
<dbl>
X3
<dbl>
1   0.0 10  0.0 
10  0.9 10  0.0 
11  1.0 10  0.0 
111 0.0 20  0.0 
112 0.1 20  0.0 
120 0.9 20  0.0 
121 1.0 20  0.0 
122 0.0 10  0.1 
1200    0.0 20  0.9 
1211    0.0 10  1.0 

since i cannot use skpr package and attributes. I hope the question is clear.


M = model.matrix(~., Alg_D$design)
normalize_between_minus_one_and_one <- function(x) {
  max_val <- max(x)
  min_val <- min(x)
  scaled <- (2 * (x - min_val) / (max_val - min_val)) - 1
  return(scaled)
}

normalized_matrix <- apply(M, 2, normalize_between_minus_one_and_one)


print(normalized_matrix)

I try this code that takes -1/1 as extreme values but the ones in the center are not normalized correctly

0

There are 0 best solutions below