How to create design matrix in r

后端 未结 6 1978
离开以前
离开以前 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条回答
  •  情话喂你
    2020-12-10 18:31

    Expanding and generalizing @Ferdinand.kraft's answer:

    dat <- data.frame(
        f1 = sample(LETTERS[1:3], 20, TRUE),
        f2 = sample(LETTERS[4:5], 20, TRUE),
        row.names = paste0("id_", 1:20))
    
    covariates <- c("f1", "f2") # in case you have other columns that you don't want to include in the design matrix
    design <- do.call(cbind, lapply(covariates, function(covariate){
        apply(outer(dat[[covariate]], unique(dat[[covariate]]), FUN = "=="), 2, as.integer)
    }))
    rownames(design) <- rownames(dat)
    colnames(design) <- unlist(sapply(covariates, function(covariate) unique(dat[[covariate]])))
    design <- design[, !duplicated(colnames(design))] # duplicated colnames happen sometimes
    design
    #       C A B D E
    # id_1  1 0 0 1 0
    # id_2  0 1 0 1 0
    # id_3  0 0 1 1 0
    # id_4  1 0 0 1 0
    # id_5  0 1 0 1 0
    # id_6  0 1 0 0 1
    # id_7  0 0 1 0 1
    

提交回复
热议问题