Building a table with values that break up a continuous variable in two groups

后端 未结 4 642
眼角桃花
眼角桃花 2021-01-19 10:31

I am looking for your help. I am trying to divide a continuous variable in two groups, I put this example about what I am trying to do:

x=data.frame(v1=c(1,1         


        
4条回答
  •  余生分开走
    2021-01-19 11:01

    Here's a data.table solution:

    require(data.table)
    x.dt <- data.table(x)
    rbindlist(lapply(v, function(i) {
        lbls <- paste0(c(">", "<="), i)
        x.dt[, grp := as.character(factor(v1 > i, levels=c(TRUE, FALSE), labels=lbls))]
        x.dt[, as.list(c(v = i, mean = mean(v1), 
            sd = sd(v1), length = length(v1))), by = grp]
    }))
    #       grp   v      mean        sd length
    #  1:  <=10  10  5.343750  2.902828     32
    #  2:   >10  10 48.500000 32.505656     18
    #  3:  <=20  20  6.216216  3.552270     37
    #  4:   >20  20 62.615385 26.809633     13
    #  5:  <=30  30  7.307692  5.907862     39
    #  6:   >30  30 69.000000 23.870484     11
    #  7:  <=50  50  9.619048 10.245647     42
    #  8:   >50  50 80.000000 17.270950      8
    #  9:  <=70  70 13.088889 16.555447     45
    # 10:   >70  70 91.000000  8.717798      5
    # 11:  <=90  90 17.625000 23.951747     48
    # 12:   >90  90 99.000000  1.414214      2
    # 13: <=110 110 20.880000 28.456655     50
    # 14: <=130 130 20.880000 28.456655     50
    # 15: <=150 150 20.880000 28.456655     50
    # 16: <=170 170 20.880000 28.456655     50
    # 17: <=190 190 20.880000 28.456655     50
    

提交回复
热议问题