Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter by vector values with for loop

Pretty new to this so…..Trying to count the number of flights that arrived at a certain location ahead of schedule in the nycflights13 dataset by carrier. Trying to do this using for loops. The steps below get me ONE result but I can’t seem to figure out the loop

#vectors for filtering
AL <- unique(flights$carrier)
LOC <- unique(flights$dest)

EARLYBIRD <- filter(flights, arr_delay < 0)

#want to repeat for "IAH" for all AL values, 
#placing each in STEP3 then move on to the 
#next value of LOC and so on.

STEP1 <- filter(EARLYBIRD, dest == "IAH")
STEP2 <- filter(STEP1, carrier == "UA")
STEP3 <- data.frame("IAH", "UA", nrow(STEP2))

I’d like to keep adding the last step to a data frame with dest, carrier, count.

Thanks for any help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use for loops for this. This is what group_by is for.

EARLYBIRD %>%
  group_by(dest, carrier) %>%
  summarize(n = n())

Or, this use case is so common there is a specialty function count:

EARLYBIRD %>% count(dest, carrier)

The above will give you the counts for all destination/carrier combinations. If you don’t want all combinations, filter out the destinations or carriers you don’t want to see first.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading