1. 数据来源于 package::nycflights13 (1) 将 flights 和 planes 进行连接,其中,最终结果应当保存 flights 中的所有 观测值并且保存 planes 中对应的观测值,并将结果命名为 flights_planes (5’) (2) 选取 flights_planes 中 tailnum 中含有字母 W 的观测值,并将选取出来的 数据框保存为新的 flights_planes(5’) (3) 剔除 flights_planes 中 engines 和 seats 缺失的观测值,然后将数据按照 engines 和 seats 分组,计算各组飞机在 2013 年的 distance 和 arr_delay 的总和,计算结果不能为 NA,将计算结果保存为新的数据 flights_sum(10’) (4) 利用上一问所得的 flights_sum,计算不同 engines 的总到达迟到时间和总 飞行距离(5’)
时间: 2023-07-14 11:12:15 浏览: 47
(1) 要连接 flights 和 planes,可以使用 dplyr 包中的 left_join 函数,代码如下:
```{r}
library(nycflights13)
library(dplyr)
flights_planes <- left_join(flights, planes, by = "tailnum")
```
这里使用 tailnum 列作为连接的条件。
(2) 要选取 flights_planes 中 tailnum 中含有字母 W 的观测值,可以使用 grepl 函数进行模式匹配,代码如下:
```{r}
flights_planes <- flights_planes[grepl("W", flights_planes$tailnum), ]
```
这里使用 [] 子集选择符和 grepl 函数进行筛选。
(3) 要剔除 flights_planes 中 engines 和 seats 缺失的观测值,可以使用 dplyr 包中的 filter 函数进行筛选,并使用 group_by 和 summarize 函数计算各组飞机在 2013 年的 distance 和 arr_delay 的总和,代码如下:
```{r}
flights_sum <- flights_planes %>%
filter(!is.na(engines) & !is.na(seats)) %>%
group_by(engines, seats) %>%
summarize(sum_distance = sum(distance, na.rm = TRUE),
sum_arr_delay = sum(arr_delay, na.rm = TRUE))
```
这里使用 %>% 管道符号和 dplyr 函数进行数据处理,其中 !is.na() 函数用于判断是否缺失,sum() 函数用于计算总和,na.rm = TRUE 表示在计算总和时忽略缺失值。
(4) 要计算不同 engines 的总到达迟到时间和总飞行距离,可以再次使用 group_by 和 summarize 函数进行计算,代码如下:
```{r}
flights_sum_engines <- flights_sum %>%
group_by(engines) %>%
summarize(sum_distance = sum(sum_distance, na.rm = TRUE),
sum_arr_delay = sum(sum_arr_delay, na.rm = TRUE))
```
这里只需要按照 engines 分组计算即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)