-2

I have a data table of quarterly observations that I want to relate to the medicaid expansion. To do this, I want a variable in my data.table (expanded_medicaid) that is 1 if the state expanded it, and 0 if it didn't. I have another data.table with the date of the expansions.

So, for example, my main data.table is like:

state_name  qtr     ...data columns
Alabama     2008 Q1  
Alabama     2008 Q2
...
Alaska      2008 Q1
Alaska      2008 Q2
... etc

and another data table has the expansion dates

state_name    qtr
Alaska        2015 Q1
Arizona       2014 Q1
Arkansas      2014 Q1
... etc

Is there a neat way I can create a column expanded_medicaid that is 1 if qtr is >= to that state's qtr in the second data.table? (This seems like it might be a job for sapply, but I've never properly understood how sapply works.)

EDIT: ideal result is for the main table to look like this:

state_name   qtr      expanded_medicaid   ...data columns
...
Alaska       2013 Q3  0
Alaska       2013 Q4  0
Alaska       2014 Q1  0
Alaska       2014 Q2  0
Alaska       2014 Q3  0
Alaska       2014 Q4  0
Alaska       2015 Q1  1
Alaska       2015 Q2  1
...
Arizona      2013 Q3  0
Arizona      2013 Q4  0
Arizona      2014 Q1  1
Arizona      2014 Q2  1
Arizona      2014 Q3  1
Arizona      2014 Q4  1
Arizona      2015 Q1  1
Arizona      2015 Q2  1
...
1
  • 1
    please provide some example data for the two tables. Expected result would also be useful. NB use dput - the format you have now is ambiguous
    – dww
    Feb 8, 2019 at 18:30

1 Answer 1

1

You could combine data.table with zoo's as.yearqtr() function to compare quarters

library(zoo)
library(data.table)

df1 <- data.table(state_name = c('Alabama', 'Arizona', 'Arkanas'),
                  qtr = c('2008 Q1', '2009 Q2', '2009 Q3'))

df2 <- data.table(state_name = c('Alabama', 'Arizona', 'Arkanas'),
                  qtr = c('2007 Q1', '2012 Q2', '2009 Q3'))

df1[, qtr := as.yearqtr(qtr, format = "%Y Q%q")]
df2[, qtr := as.yearqtr(qtr, format = "%Y Q%q")]

df1[df2, on = .(state_name), expanded_medicaid := as.integer(qtr >= i.qtr)]

#   state_name     qtr expanded_medicaid
#1:    Alabama 2008 Q1                 1
#2:    Arizona 2009 Q2                 0
#3:    Arkanas 2009 Q3                 1
1
  • Perfect. I had no idea data.table could do joins like this! Feb 8, 2019 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.