lundi 17 juillet 2017

ifelse do nothing in r

I'm a very novice R programmer, and I'm trying to convert old SAS code to R. I need to replace values based on a condition, and if the condition is false, leave them alone. I've googled this and tried many of the solutions posted, but to no avail. The reason I'm doing this is to categorize the first instance of an event (in this case physicians writing a prescription). if the first month they wrote a prescription was May of last year, their beginning month(newwriter) is 5. If it was in June, then 6 etc. I'm working backwards from June of this year, and I want to update their beginning month(newwriter) if an earlier prescription is found. If no earlier prescription is found, I want to leave the number alone. This is the code I'm using:

newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_05_31_2017>0,17,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_04_30_2017>0,16,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_03_31_2017>0,15,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_02_28_2017>0,14,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_01_31_2017>0,13,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_12_31_2016>0,12,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_11_30_2016>0,11,NULL)
newwriters$newwriter=ifelse(newwriters$MTRx_10_31_2016>0,10,NULL)

The problem is that it keeps changing higher values to 0 if it doesn't find a prescription in that month. I want it to just leave the values alone. I've tried all of the following as well with no success:

newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,newwriters$newwriter)
newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,newwriters[,16])
newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,)

As I mentioned, I'm new to writing R code. I'm sure there's a better/faster/more efficient way of doing this, but I'm not sure what else to try. Thanks in advance for your help!

Aucun commentaire:

Enregistrer un commentaire