R - extract a cell value using conditions

Viewed 479

I am trying to use a specific cell value from my dataframe as an object (for later multiplication with other values in the variable, e.g. I want the content of def for the year= 2019). I do not want to refer to this value via indexing with row/column numbers (large data set).


The following code works for me:

def2019 <- df %>%
  subset(year =="2019") %>%
  select(def)
def2019 <- def2019[1,1]
def2019 <- as.vector(def2019$def, mode='numeric') to enable multiplication later

But: it is not very fast and also quite hackish. Is there a more generalizable/elegant solution to this problem?


MRE:

df <- tribble(~year, ~value,~def,
              "2017", 1, 0.9,
              "2017", 2, 0.9,
              "2018", 3, 1,
              "2019", 4, 1.1,
              "2019", NA, 1.1,
              "2019", 6, 1.1,
              "2019", 9, 1.1)
1 Answers

If we need an efficient option, use data.table

library(data.table)
def2019 <- setDT(df, key = 'year')["2019", .(def = def[1])]$def

If the column 'year' is integer class

setDT(df, key = 'year')[.(2019), .(def = def[1])]$def
Related