How to create design matrix in r

后端 未结 6 1980
离开以前
离开以前 2020-12-10 17:40

I have two factors. factor A have 2 level, factor B have 3 level.

How to create the following design matrix?

     factorA1 factorA2 factorB1 factorB         


        
6条回答
  •  猫巷女王i
    2020-12-10 18:22

    Assuming your data in in a data.frame called dat, let's say the two factors are given as in this example:

    > dat <- data.frame(f1=sample(LETTERS[1:3],20,T),f2=sample(LETTERS[4:5],20,T),id=1:20)
    > dat
       f1 f2 id
    1   C  D  1
    2   B  E  2
    3   B  E  3
    4   A  D  4
    5   C  E  5
    6   C  E  6
    7   C  D  7
    8   B  E  8
    9   C  D  9
    10  A  D 10
    11  B  E 11
    12  C  E 12
    13  B  D 13
    14  B  E 14
    15  A  D 15
    16  C  E 16
    17  C  D 17
    18  C  D 18
    19  B  D 19
    20  C  D 20
    > dat$f1
     [1] C B B A C C C B C A B C B B A C C C B C
    Levels: A B C
    > dat$f2
     [1] D E E D E E D E D D E E D E D E D D D D
    Levels: D E
    

    You can use outer to get a matrix as you showed, for each factor:

    > F1 <- with(dat, outer(f1, levels(f1), `==`)*1)
    > colnames(F1) <- paste("f1",sep="=",levels(dat$f1))
    > F1
          f1=A f1=B f1=C
     [1,]    0    0    1
     [2,]    0    1    0
     [3,]    0    1    0
     [4,]    1    0    0
     [5,]    0    0    1
     [6,]    0    0    1
     [7,]    0    0    1
     [8,]    0    1    0
     [9,]    0    0    1
    [10,]    1    0    0
    [11,]    0    1    0
    [12,]    0    0    1
    [13,]    0    1    0
    [14,]    0    1    0
    [15,]    1    0    0
    [16,]    0    0    1
    [17,]    0    0    1
    [18,]    0    0    1
    [19,]    0    1    0
    [20,]    0    0    1
    

    Now do the same for the second factor:

    > F2 <- with(dat, outer(f2, levels(f2), `==`)*1)
    > colnames(F2) <- paste("f2",sep="=",levels(dat$f2))
    

    And cbind them to get the final result:

    > cbind(F1,F2)
    

提交回复
热议问题