Grouping and counting to get a closerate

走远了吗. 提交于 2019-12-04 02:31:39
aggregate(list(output = df$status == "closed"),
          list(country = df$country),
          function(x)
              c(close = sum(x),
                open = length(x) - sum(x),
                rate = mean(x)))
#  country output.close output.open output.rate
#1      BE         3.00        1.00        0.75
#2      NL         3.00        2.00        0.60

There was a solution using table in the comments which appears to have been deleted. Anyway, you could also use table

output = as.data.frame.matrix(table(df$country, df$status))
output$closerate = output$closed/(output$closed + output$open)
output
#   closed open closerate
#BE      3    1      0.75
#NL      3    2      0.60

You can use tapply:

data.frame(open=tapply(df$status=="open", df$country, sum),
           closed=tapply(df$status=="closed", df$country, sum)
           closerate=tapply(df$status=="closed", df$country, mean))`

A data.table method would be.

library(data.table)
setDT(df)[, {temp <- status=="closed"; # store temporary logical variable
            .(closed=sum(temp), open=sum(!temp), closeRate=mean(temp))}, # calculate stuff
          by=country] # by country

which returns

   country closed open closeRate
1:      BE      3    1      0.75
2:      NL      3    2      0.60

Here is a dplyr solution.

output <- df %>%
  count(country, status) %>%
  group_by(country) %>%
  mutate(total = sum(n)) %>%
  mutate(percent = n/total)

Returns...

output
country status   n total percent
BE      closed   3  4    0.75
BE      open     1  4    0.25
NL      closed   3  5    0.60
NL      open     2  5    0.40

Here's a quick solution with tidyverse:

library(dplyr)
df %>% group_by(country) %>% 
  mutate(status =ifelse(closeday < '2017-08-20', 'open', 'closed'),
         closerate=mean(status=="closed"))

Returning:

# A tibble: 9 x 5
# Groups:   country [2]
  customer country   closeday status closerate
     <dbl>  <fctr>     <date>  <chr>     <dbl>
1        1      BE 2017-08-23 closed      0.75
2        2      NL 2017-08-05   open      0.60
3        3      NL 2017-08-22 closed      0.60
4        4      NL 2017-08-26 closed      0.60
5        5      BE 2017-08-25 closed      0.75
6        6      NL 2017-08-13   open      0.60
7        7      BE 2017-08-30 closed      0.75
8        8      BE 2017-08-05   open      0.75
9        9      NL 2017-08-23 closed      0.60

Here I am utilizing the coercion of logicals into integer when the vector of TRUE/FALSE is put into the mean() function.

Alternatively, with data.table:

library(data.table)
setDT(df)[,status:=ifelse(closeday < '2017-08-20', 'open', 'closed')]
df[, .(closerate=mean(status=="closed")), by=country]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!