Extend contigency table with proportions (percentages)

后端 未结 6 1210
悲哀的现实
悲哀的现实 2020-11-29 02:39

I have a contingency table of counts, and I want to extend it with corresponding proportions of each group.

Some sample data (tips data set from gg

6条回答
  •  心在旅途
    2020-11-29 02:49

    I am not 100% certain, but I think this does what you want using prop.table. See mostly the last 3 lines. The rest of the code is just creating fake data.

    set.seed(1234)
    
    total_bill <- rnorm(50, 25, 3)
    tip <- 0.15 * total_bill + rnorm(50, 0, 1)
    sex <- rbinom(50, 1, 0.5)
    smoker <- rbinom(50, 1, 0.3)
    day <- ceiling(runif(50, 0,7))
    time <- ceiling(runif(50, 0,3))
    size <- 1 + rpois(50, 2)
    my.data <- as.data.frame(cbind(total_bill, tip, sex, smoker, day, time, size))
    my.data
    
    my.table <- table(my.data$smoker)
    
    my.prop <- prop.table(my.table)
    
    cbind(my.table, my.prop)
    

提交回复
热议问题