Create summary table of categorical variables of different lengths

后端 未结 6 644
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 11:04

In SPSS it is fairly easy to create a summary table of categorical variables using \"Custom Tables\":

\"This

6条回答
  •  情歌与酒
    2021-01-02 11:37

    You may find the following code snippet useful. It utilizes the base package functions table, margin.table, and prop.table and does not require any other packages. It does collect the results to a list with named dimensions however (these could be collected to a single matrix with rbind):

    dat <- table(mtcars[,8:11])
    result <- list()
    for(m in 1:length(dim(dat))){
        martab <- margin.table(dat, margin=m)
        result[[m]] <- cbind(Freq=martab, Prop=prop.table(martab))
    }
    names(result) <- names(dimnames(dat))
    
    > result
    $vs
      Freq   Prop
    0   18 0.5625
    1   14 0.4375
    
    $am
      Freq    Prop
    0   19 0.59375
    1   13 0.40625
    
    $gear
      Freq    Prop
    3   15 0.46875
    4   12 0.37500
    5    5 0.15625
    
    $carb
      Freq    Prop
    1    7 0.21875
    2   10 0.31250
    3    3 0.09375
    4   10 0.31250
    6    1 0.03125
    8    1 0.03125
    

提交回复
热议问题