【问题标题】:What is this arrange function in the second line doing here?第二行的这个排列函数在这里做什么?
【发布时间】:2021-01-25 05:59:28
【问题描述】:

当我遇到这段代码时,我目前正在审查 R for Data Science。 这段代码的问题如下。我不明白这里 arrange 功能的必要性。 arrange 函数不只是重新排列行吗?

library(tidyverse)
library(nycflights13))
flights %>%
arrange(tailnum, year, month, day) %>%
group_by(tailnum) %>%
mutate(delay_gt1hr = dep_delay > 60) %>%
mutate(before_delay = cumsum(delay_gt1hr)) %>%
filter(before_delay < 1) %>%
count(sort = TRUE)

但是,无论有没有排列功能,它的输出都会有所不同,如下所示:

#with the arrange function
tailnum     n
   <chr>   <int>
 1 N954UW    206
 2 N952UW    163
 3 N957UW    142
 4 N5FAAA    117
 5 N38727     99
 6 N3742C     98
 7 N5EWAA     98
 8 N705TW     97
 9 N765US     97
10 N635JB     94
# ... with 3,745 more rows

#Without the arrange function
tailnum     n
   <chr>   <int>
 1 N952UW    215
 2 N315NB    161
 3 N705TW    160
 4 N961UW    139
 5 N713TW    128
 6 N765US    122
 7 N721TW    120
 8 N5FAAA    117
 9 N945UW    104
10 N19130    101
# ... with 3,774 more rows

如果您能帮助我理解这一点,我将不胜感激。为什么必须在此处包含 arrange 函数?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    是的,arrange 只是对行进行排序,但您在更改结果之后进行过滤。

    这是一个简化的示例,用于演示使用和不使用arrange 时的输出有何不同。

    library(dplyr)
    df <- data.frame(a = 1:5, b = c(7, 8, 9, 1, 2))
    
    df %>% filter(cumsum(b) < 20)
    #  a b
    #1 1 7
    #2 2 8
    
    df %>% arrange(b) %>% filter(cumsum(b) < 20)
    #  a b
    #1 4 1
    #2 5 2
    #3 1 7
    #4 2 8
    

    【讨论】:

    • 非常感谢!你的回答很棒。但是这里为什么要使用arrange函数呢?
    • 原始数据按daymonthyear排序。使用arrange,我们首先按tailnum对它们进行排序,在每个tailnum中,航班按daymonthyear排序。
    猜你喜欢
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多