0

I have a data set of patient data. I am trying to figure out if the patients who switched medications throughout the study switched medications before an event occurred. Right now I have made a new data.frame using the code below:

switches_MACE <- matrix(0, nrow=dim(WorkingDifMed3)[1], ncol=4)
colnames(switches_MACE) <- c("record_id", "WhenSwitch","MACE_date","Before_or_After")

I have easily transferred over the record_id and the MACE_date as I can easily transfer the whole column from a prior data.frame (WorkingDifMed3).

The problem I am having is the creation of the "When Switch" column. I am trying to use a nested if statement within a for loop. My "WorkingDifMed3" data.frame columns are set up so that the record_id is first(733 patients, each a new row), the med given at discharge, then "x" amount of columns which are not to be used, the date the medication switch/non-switch occurred (the column being compared to the discharge column), then the medication (0,1,2,3). The medication switch non-switch column and date columns are repeated out to the end of the study.

The code I have is as followed:

A= 1:733


for (i in seq(along=A))
  {
  for (j in seq(from=start, to=dim(WorkingDifMed3)[2], by=2))
    {
    if(WorkingDifMed3[i,"p2y12i_fu_discharge"] != (WorkingDifMed3[i,j]))
    {switches_MACE[i,2] <- WorkingDifMed3[i,j+1]}
  }
}

The issue is that the code returns 0, 1, TRUE and FALSE. I'm not sure why as I need it to return the date (listed prior to the medication) at which the discharge medication (listed after the date it potentially changed) does NOT equal the medication in the discharge column.

Realize that for patient 1 the medication may change at time 8 where patient 2 may change medication at time 1 so not all dates are the same.

Thank you!

  • It’s difficult to follow what you’re doing without example data. You might consider including a minimal dataset that’s in the same format as what you’re working with (https://stackoverflow.com/a/5963610/12446618). Also, I suspect your code could be simplified by writing a function that works for a single row and then using the `apply` function to apply it all rows. – ngwalton Jun 20 '21 at 07:35

0 Answers0