如何用dplyr计算分摊率?

bkkx9g8r  于 2023-04-03  发布在  其他
关注(0)|答案(3)|浏览(117)

我有一个数据集,如下所示:

data <- tribble(
  ~id,     ~click,  ~engagement,
   1,         1,          0,
   2,         2,          3,         
   3,         3,          5,
   4,         4,          6, 
   5,         5,          2,
   6,         3,          4,
   7,         8,          7,
   8,         6,          1,
   9,         7,          6,
  10,         7,          3,
)

我想要的数据是这样的:

new_data <- tribble(
  ~total_click,  ~total_engagement, ~percantage_click, ~percantage_engagement, 
     46,              37,              0.5542169,          0.4457831,
)

我可以通过这样的代码获得total_click和total_engagement:

data %>% 
  summarise(total_click = sum(click), total_engagement = sum(engagement))

我怎样才能得到百分比?

balp4ylt

balp4ylt1#

这个怎么样?

data %>% 
  summarise(total_click = sum(click), total_engagement = sum(engagement), 
            percantage_click=total_click/(total_click+total_engagement), 
            percantage_engagement=1- percantage_click)

数据:

data <- tribble(
  ~id,     ~click,  ~engagement,
  1,         1,          0,
  2,         2,          3,         
  3,         3,          5,
  4,         4,          6, 
  5,         5,          2,
  6,         3,          4,
  7,         8,          7,
  8,         6,          1,
  9,         7,          6,
  10,         7,          3,
)
wnavrhmk

wnavrhmk2#

data %>%
    summarize_at(vars(-id), sum) %>%
    mutate(click_p = click/(click + engagement),
           engagement_p = 1 - click_p)
## A tibble: 1 x 4
#  click engagement click_p engagement_p
#  <dbl>      <dbl>   <dbl>        <dbl>
#1    46         37   0.554        0.446
bprjcwpo

bprjcwpo3#

我们也可以这样做:

data %>% 
  summarise_at(vars(-id), list(sum)) %>% 
  bind_cols(. / rowSums(.))

相关问题