I am trying to write a function get_value <- function(gyear, gmonth) that selects a row from already existing dataframe or a value if the month is between two time points. The dataframe is e.g.
df <- read.table(header = TRUE, text = "
year month var1 var2
2022 1 123 987
2021 4 234 876
2021 1 345 765
2020 7 456 654
2020 3 567 543
2020 1 678 432
2019 1 789 321")
For example in year 2021 the same row
year month var1 var2
2021 1 345 765
is valid for months 1,2,3 and then comes a change and the next row
year month var1 var2
2021 4 234 876
is valid for months 4,5,6,7,8,9,10,11,12.
If the year & month are already in the dataframe, then I can have the row like
get_value <- function(gyear, gmonth){
library(tidyverse)
temp <- df %>% filter(year == gyear & month == gmonth)
}
get_value(gyear = 2020, gmonth = 1)
but what I want is also to be able to have rows (months) that are between the months that are included in the dataframe. For example I would like to be able to call
get_value(gyear = 2021, gmonth = 5)
that returns row
year month var1 var2
2021 4 234 876
because in year 2021 the month is between 4-12.
Thanks in advance for your help!