![]() It has an explicit treatment for NAs which make it more robust and it is also slightly faster. ![]() If you want to use ifelse, you could do something like: writers$newwriter=ifelse(newwriters$MTRx_06_30_2017>0 & !is.na(newwriters$MTRx_06_30_2017),18,newwriters$newwriter)īut you might also consider doing writers$newwriter = 18īetter is to use if_else from package dplyr. Probably does not work as expected because there are there NULL or NA values in those columns. So in your specific case, writers$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,newwriters$newwriter) When doing b, we only replace values where a>2 is TRUE, and since NA is not TRUE, the value for the third entry is simply not altered. The intuitive reason for this is that NA>3returns not TRUE or FALSE, but NA, so ifelse does not know which of the two fields to return. Now, compare the results of the following two snippets: b = c(1,1,1,1,1) However, now let's replace one of the values in a, with NA, let's say a = c(1,2,NA,4,5) They will both result in b being 1 1 2 2 2. Here are two ways to achieve what you want: b = 2 Now, let's say we want to replace values in b with 2, if the value in a is larger than 3. If you want to change a column (or vector) conditionally, and leave entries untouched where the condition is not satisfied, you could probably also do without ifelse.Ĭonsider the following two vectors: a = c(1,2,3,4,5) I'm sure there's a better/faster/more efficient way of doing this, but I'm not sure what else to try. Newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,)Īs I mentioned, I'm new to writing R code. Newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,newwriters) I've tried all of the following as well with no success: newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,newwriters$newwriter) I want it to just leave the values alone. The problem is that it keeps changing higher values to 0 if it doesn't find a prescription in that month. ![]() This is the code I'm using: newwriters$newwriter=ifelse(newwriters$MTRx_06_30_2017>0,18,NULL) If no earlier prescription is found, I want to leave the number alone. 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 the first month they wrote a prescription was May of last year, their beginning month(newwriter) is 5. The reason I'm doing this is to categorize the first instance of an event (in this case physicians writing a prescription). I've googled this and tried many of the solutions posted, but to no avail. I need to replace values based on a condition, and if the condition is false, leave them alone. I'm a very novice R programmer, and I'm trying to convert old SAS code to R.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |