繁体   English   中英

基于数据框 R 子集的一列中“分类值”的百分比

[英]Percentages of "categorical values" in one column based on subset of data frame R

我的数据由名为 data$engine、data$unit 和 data$Turn 的三列(作为示例)组成。 data$Turn 是具有值 0、1 和 2 的分类变量。对于 data$engine 的每个唯一值,data$unit 可以有多个值。

我想分别为唯一的 data$unit 和 data$engine 计算 data$Turn 中 0、1 和 2 的百分比。 我有十万行,但我只为 data$engine 的两个唯一值粘贴数据结构...请注意,每个 data$unit(对于特定的 data$engine)可以有数千行,因此用于计算 %ages ,我想继续:

%age of 0's for data$unit 207 and data$engine 1111 = 
counts of all zeros within data$unit 207 and data$engine 1111 (DIVIDED BY) 
summation of all counts of 0, 1, and 2 for this data$unit and data$engine.*emphasized text*

Similarly for % ages of 1's and 2's for data$unit 207 and data$engine 1111, 
and it continues for all other values of units and engines....

data$engine  data$unit     data$AvailableLeft
    1111       207                1
    1111       207                0
    1111       207                2
    1111       207                0
    1111       207                0
    1111       207                2
    1111       207                0
    1111       207                1
    1111       208                0
    1111       208                1
    1111       208                2
    1111       208                1
    1122       209                2
    1122       209                2
    1122       209                0
    1122       209                0
    1122       209                1

我想以这种方式获得我的输出,即为每个 data$unit 和每个 data$engine 获得 0、1 和 2s 的平均百分比:

data$engine  data$unit     %age of 0s     %age of 1s    %age of 2s
 1111          207              ?              ?            ?
 1111          208              ?              ?            ?    
 1122          209              ?              ?            ?    
   .             .                    .
   .             .                    .
   .             .                    .

你可以使用data.table

library(data.table)
setDT(data)[, .(p0=sum(AvailableLeft==0)/.N, 
                p1=sum(AvailableLeft==1)/.N, 
                p2=sum(AvailableLeft==2)/.N), 
             keyby=.(data, engine, unit)]

   engine unit   p0   p1   p2
1:   1111  207 0.50 0.25 0.25
2:   1111  208 0.25 0.50 0.25
3:   1122  209 0.40 0.20 0.40
library(data.table)
dt <- as.data.table(your_data)
dt[,.("p1"=paste(as.character(round(sum(data.AvailableLeft==1)*100/.N,2)),"%")),.(data.engine,data.unit)]

我会留下% of data.AvailableLeft==0% of data.AvailableLeft==2因为从这里找出它们是微不足道的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM