filter函数使用及NYC机场航班数据展示相关技术问题咨询
Hey Sara, let's work through your questions step by step, using R's nycflights13 package since you referenced the flights and airports datasets:
filter() (and clarifying variable selection) First, a quick clarification: filter() from the dplyr package is used to subset rows based on conditions (like "only flights in January"). If you mean "select specific variables/columns" (not rows), you'll want select() instead. Let's cover both:
Filter rows based on criteria:
For example, get all flights departing in January:library(dplyr) library(nycflights13) january_flights <- flights %>% filter(month == 1)Select specific variables/columns:
If you want to keep only the airport of origin, destination, and departure time:selected_columns <- flights %>% select(origin, dest, dep_time)Combine both: Filter rows AND select columns:
jan_selected <- flights %>% filter(month == 1) %>% select(origin, dest, dep_time)
NYC's major commercial airports represented in the flights dataset are 3 total: EWR (Newark Liberty International), JFK (John F. Kennedy International), and LGA (LaGuardia Airport).
To find which has the most flights, count departures per airport:
airport_flight_counts <- flights %>% count(origin, sort = TRUE)
Running this will show EWR has the highest volume (120,835 flights), followed by JFK (111,279) and LGA (104,662).
To visualize this with a bar graph using ggplot2:
library(ggplot2) ggplot(airport_flight_counts, aes(x = origin, y = n)) + geom_bar(stat = "identity", fill = "#3498db") + labs(title = "Total Flights from NYC Airports", x = "Airport Code", y = "Number of Flights") + theme_light()
This will produce a clean bar chart comparing flight volumes across the three airports.
flights and airports It sounds like your code is either missing a join between the two datasets, or accidentally extracting a single vector instead of keeping a full data frame. Here's how to fix it:
Join the datasets: Link
flights(which usesoriginfor airport codes) withairports(which usesfaafor codes):flights_with_airport_data <- flights %>% left_join(airports, by = c("origin" = "faa"))Filter for NYC airports: Keep only rows for the three NYC-area airports:
nyc_airport_flights <- flights_with_airport_data %>% filter(origin %in% c("EWR", "JFK", "LGA"))View relevant details: If you want to see airport-specific info (like full name, location) alongside flight data, use
select()to pick columns:nyc_airport_details <- nyc_airport_flights %>% select(origin, name, lat, lon, dep_time, dest)
If your old code only returned one variable, check if you used pull() instead of select() — pull() extracts a single column as a vector, while select() preserves the data frame structure with all your chosen columns.
内容的提问来源于stack exchange,提问作者Sara

