0

This should be a common question, but I was only able find an old question with a complicated answer here. Say I have a table for flight delays and I want to select specific delay time based on attributes like direction and week?

df<- data.frame(
  Quarter = paste0("Q", rep(1:4, each = 4)),
  Week = rep(c(1:8), each = 2, times = 1),
  Direction = rep(c("Inbound", "Outbound"), times = 8),
  Delay = c(10.8, 9.7, 15.5, 10.3, 11.8, 8.9, 5.5,
            3.3, 10.6, 8.8, 6.6, 5.2, 9.1, 7.3, 5.3, 4.4)
)

A proposed answer of the above post look like this:df[df[,"Week"]=="1" & df[,"Direction"]=="Outbound","Delay"]. Is there a better way to do this without repeating data frame name, something simpler in tidyverse? I want to select a single element at a time, something like subsetting with [[

Kabocha Porter
  • 301
  • 3
  • 8

1 Answers1

0

You can use filter and select :

library(dplyr)

df %>%
  filter(Quarter == 'Q1', Direction == 'Inbound') %>%
  select(Delay)

#  Delay
#1  10.8
#2  15.5

If you need a vector as output use pull instead of select.


In base R, you can do this as :

subset(df, Quarter == 'Q1' & Direction == 'Inbound', select = Delay)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Hi thx for the answer. I modified my q a bit. My example wasn't accurate. I want to select a single element, instead of a subset or a data frame. I see that `subset` and or piping with `select` return a list instead. – Kabocha Porter Apr 05 '21 at 03:24
  • How is the modified version any different? You can do `df %>% filter(Week == 1, Direction == 'Outbound') %>% pull(Delay)` or with `subset`, `subset(df, Week == 1 & Direction == 'Outbound')$Delay` . Is that what you want? – Ronak Shah Apr 05 '21 at 03:32
  • list contains name of the variable. But I want to get the number only. So basically after I use `subset`, I still need to use `[[` to extract the number. ```> result[[1]] [1] 10.8 ``` – Kabocha Porter Apr 05 '21 at 03:43
  • 1
    If you use the code from my comment above `result <- subset(df, Week == 1 & Direction == 'Outbound')$Delay` you don't need `[[`. – Ronak Shah Apr 05 '21 at 03:49