使用dplyr,自定义函数或purr的多条件if-else

时间:2018-08-26 17:40:30

标签: r dplyr purrr

我有一个数据框,其结构类似于以下内容:

set.seed(123)  
df<-data_frame(SectionName = rep(letters[1:2], 50),
               TimeSpentSeconds = sample(0:360, 100, replace = TRUE),
               Correct = sample(0:1, 100, replace = TRUE))

我想通过取落入一定范围(小于30、30-60、60-90,...,大于180)的所有TimeSpentSeconds值来汇总此数据帧,将时间标记为这些范围,将它们按SectionName分组,然后找到“正确”列的总和,以使结果数据框看起来像这样:

    TimeGroup             SectionName Correct
   <fct>                 <chr>         <int>
 1 LessThan30Secs        a                 2
 2 LessThan30Secs        b                 3
 3 30-60 Seconds         a                 4
 4 30-60 Seconds         b                 3
 5 60-90 Seconds         a                 2
 6 60-90 Seconds         b                 3
 7 90-120 Seconds        a                 4
 8 90-120 Seconds        b                 0
 9 120-150 Seconds       a                 4
10 120-150 Seconds       b                 0
11 150-180 Seconds       a                 1
12 150-180 Seconds       b                 2
13 GreaterThan180Seconds a                11
14 GreaterThan180Seconds b                11

我可以使用以下if-else代码成功完成此操作,在该代码中,我一直将所有时间都突变为带有适当标签,分组并汇总的新列:

x <- c("LessThan30Secs", "30-60 Seconds", "60-90 Seconds","90-120 Seconds", 
           "120-150 Seconds", "150-180 Seconds", "GreaterThan180Seconds") 

df %>% 
mutate(TimeGroup = if_else(TimeSpentSeconds >= 0 & TimeSpentSeconds <= 30, "LessThan30Secs",
                if_else(TimeSpentSeconds > 30 & TimeSpentSeconds <= 60, "30-60 Seconds",
                if_else(TimeSpentSeconds > 60 & TimeSpentSeconds <= 90, "60-90 Seconds",
                if_else(TimeSpentSeconds > 90 & TimeSpentSeconds <= 120, "90-120 Seconds",
                if_else(TimeSpentSeconds > 120 & TimeSpentSeconds <= 150, "120-150 Seconds", 
                if_else(TimeSpentSeconds > 150 & TimeSpentSeconds <= 180, "150-180 Seconds",
                if_else(TimeSpentSeconds > 180, "GreaterThan180Seconds", "")))))))) %>%
    mutate(TimeGroup = factor(TimeGroup, levels = x)) %>%
    arrange(TimeGroup) %>%
    group_by(TimeGroup, SectionName) %>%
    summarise(Correct = sum(Correct))

但是,只有一种更好的方法可以做到这一点。我考虑过编写函数,但是由于我对函数编写的了解不高,所以并没有走太远。

有没有人想出一种更优雅的方式来通过我没想到的dplyr方法来完成相同的输出,编写自定义函数,也许在某个时候使用purrr包,或其他一些r函数? >

3 个答案:

答案 0 :(得分:3)

我们可以使用cut(或findInterval)而不是多个嵌套的ifelse语句轻松地做到这一点

lbls <- c('LessThan30secs', '30-60 Seconds', '60-90 Seconds', 
    '90-120 Seconds', '120-150 Seconds', '150-180 Seconds', 'GreaterThan180Seconds')
df %>% 
    group_by(TimeGroup = cut(TimeSpentSeconds, 
                 breaks = c(seq(0, 180, by = 30), Inf), labels = lbls), 
            SectionName) %>%
   summarise(Correct = sum(Correct)) %>%
   na.omit

答案 1 :(得分:3)

case_when()将做您想要的。这是嵌套ifelse()语句的一种很好的替代方案。

library(dplyr)

mutate(df,
       TimeGroup = case_when(
         TimeSpentSeconds >= 0 & TimeSpentSeconds <= 30 ~ "Less Than 30 Secs",
         TimeSpentSeconds > 30 & TimeSpentSeconds <= 60 ~ "30-60 Seconds",
         TimeSpentSeconds > 60 & TimeSpentSeconds <= 90 ~ "60-90 Seconds",
         TimeSpentSeconds > 90 & TimeSpentSeconds <= 120 ~ "90-120 Seconds",
         TimeSpentSeconds > 120 & TimeSpentSeconds <= 150 ~ "120-150 Seconds", 
         TimeSpentSeconds > 150 & TimeSpentSeconds <= 180 ~ "150-180 Seconds",
         TimeSpentSeconds > 180 ~ "Greater Than 180 Seconds",
         TRUE ~ "NA")
)

最后一个参数是所有不符合任何条件的记录的全部内容,例如时间不到0秒。

答案 2 :(得分:1)

``` r
library(tidyverse)
set.seed(123)
df<-data_frame(SectionName = rep(letters[1:2], 50),
               TimeSpentSeconds = sample(0:360, 100, replace = TRUE),
               Correct = sample(0:1, 100, replace = TRUE))

time_spent_range <- function(value, start, end, interval) {
  end <- end + (end%%interval) # make sure the end value is divisible by the interval
  bins_start <- seq(start, end - interval, by = interval)
  bins_end <- seq(start + interval, end, by = interval)
  bins_tibble <- tibble(bin_start = bins_start, 
                        bin_end = bins_end) %>% 
    mutate(in_bin = if_else((value > bin_start|(value == 0 & bin_start == 0)) 
                            & value <= bin_end,
                            1,
                            0)) %>% 
    filter(in_bin == 1)
  bin <- paste0(as.character(bins_tibble$bin_start[1]), 
                '-', 
                as.character(bins_tibble$bin_end[1]),
                ' Seconds')
  return(bin)
}

df %>% 
  mutate(TimeGroup = map_chr(TimeSpentSeconds, time_spent_range, start = 0, end = max(df$TimeSpentSeconds) , interval = 30))
#> # A tibble: 100 x 4
#>    SectionName TimeSpentSeconds Correct TimeGroup      
#>    <chr>                  <int>   <int> <chr>          
#>  1 a                        103       1 90-120 Seconds 
#>  2 b                        284       0 270-300 Seconds
#>  3 a                        147       0 120-150 Seconds
#>  4 b                        318       1 300-330 Seconds
#>  5 a                        339       0 330-360 Seconds
#>  6 b                         16       1 0-30 Seconds   
#>  7 a                        190       1 180-210 Seconds
#>  8 b                        322       1 300-330 Seconds
#>  9 a                        199       0 180-210 Seconds
#> 10 b                        164       0 150-180 Seconds
#> # ... with 90 more rows
```

reprex package(v0.2.0)于2018-08-26创建。