使用 R 中的 mutate 函数进行数据转换

data transformation using the mutate function in R

我安装了 nycflights13 包和 tidyverse

这是航班数据集的前6行

    head(flights)
# A tibble: 6 x 19
   year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin
  <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>    <int> <chr>   <chr> 
1  2013     1     1      517            515         2      830            819        11 UA        1545 N14228  EWR   
2  2013     1     1      533            529         4      850            830        20 UA        1714 N24211  LGA   
3  2013     1     1      542            540         2      923            850        33 AA        1141 N619AA  JFK   
4  2013     1     1      544            545        -1     1004           1022       -18 B6         725 N804JB  JFK   
5  2013     1     1      554            600        -6      812            837       -25 DL         461 N668DN  LGA   
6  2013     1     1      554            558        -4      740            728        12 UA        1696 N39463  EWR   
with 19 variables: year <int>, month <int>, day <int>, dep_time <int>, sched_dep_time <int>, dep_delay <dbl>,
arr_time <int>, sched_arr_time <int>, arr_delay <dbl>, carrier <chr>, flight <int>, tailnum <chr>, origin <chr>,
dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>, time_hour <dttm>

我正在尝试做两件事。

这是我的代码运行。我使用 select 函数创建了我的数据 table。我使用 mutate 函数创建了新列,但我无法编写一行代码来计算每行或目标的比例(有 336,776 行)

new.table<-select(flights, dest, month, day, dep_time, carrier, flight, arr_delay)
mutate(new.table, arr_delay_prop=sum(arr_delay)/(1:336776))

我知道我需要使用 sum 函数来计算到达延迟的总和,但我不确定如何将每行占总数的比例 arr_delay。

你想要这个吗?

mutate(new.table, arr_delay_prop=arr_delay/sum(arr_delay, na.rm = T))

# A tibble: 336,776 x 8
   dest  month   day dep_time carrier flight arr_delay arr_delay_prop
   <chr> <int> <int>    <int> <chr>    <int>     <dbl>          <dbl>
 1 IAH       1     1      517 UA        1545        11     0.00000487
 2 IAH       1     1      533 UA        1714        20     0.00000886
 3 MIA       1     1      542 AA        1141        33     0.0000146 
 4 BQN       1     1      544 B6         725       -18    -0.00000797
 5 ATL       1     1      554 DL         461       -25    -0.0000111 
 6 ORD       1     1      554 UA        1696        12     0.00000532
 7 FLL       1     1      555 B6         507        19     0.00000842
 8 IAD       1     1      557 EV        5708       -14    -0.00000620
 9 MCO       1     1      557 B6          79        -8    -0.00000354
10 ORD       1     1      558 AA         301         8     0.00000354
# ... with 336,766 more rows