计算分箱数据的相对百分比

时间:2021-02-22 16:02:25

标签: r

我有一个数据,我想计算每个 $args = array( 'post_type' => 'my_new_post_type', 'meta_query' => array( 'relation' => 'AND', 'firstArray_clause' => array( 'key' => 'my_first_key', 'value' => 'My first value', 'compare' => 'EXISTS', ), 'secondArray_clause' => array( 'key' => 'my_second_key', 'compare' => 'EXISTS', ), ), 'orderby' => array( 'firstArray_clause' => 'ASC', ), ); $MyQuery = new WP_Query( $args); 中数据中包含的列 tag 的相对百分比,并将其绘制为堆积条形图。

bin

因此,在这种情况下,bin df <- data.frame(tag = c("a", "b", "a", "c", "d", "d", "b", "a"), tag_id = c(12, 45, 12, 43, 50, 50, 45, 12), value = c(40, 11, 40, 12, 20, 22, 27, 29)) break_label <- c(10,20,30,40) tag_label <- c("10-20","20-30", "30-40") df$bin <- cut(df$value,breaks = break_label,labels = tag_label) 中的 b, c, and d 将分别为 33.3% 和 10-20 为 0%。 我该如何计算?

2 个答案:

答案 0 :(得分:2)

我们也可以在 prop.table 中使用 table + base R

prop.table(table(df[c('tag', 'bin')]), 1)

答案 1 :(得分:1)

这是一种方法,依赖于对数据进行两次整形以用 0 填充不存在的条目

library(tidyverse)
df %>%
    count(tag, bin) %>%
    pivot_wider(names_from = bin, 
                values_from = n, 
                values_fill = 0) %>%
    pivot_longer(cols = -tag) %>%
    group_by(tag) %>%
    mutate(perc_n = value/sum(value))

 #   tag   name  value perc_n
 # 1 a     20-30     1  0.333
 # 2 a     30-40     2  0.667
 # 3 a     10-20     0  0    
 # 4 b     20-30     1  0.5 
 # ...
相关问题