Created
September 26, 2016 21:04
-
-
Save bhive01/40e6296604cead0050e1f73384203cb8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(tidyverse) | |
| dt <- tibble(V1=c(1,2,4), V2=c("a","a","b"), V3=c(2,3,1)) | |
| swap_if<- function (condition, val1, val2, missing = NA) | |
| { | |
| if (!is.logical(condition)) { | |
| stop("`condition` must be logical", call. = FALSE) | |
| } | |
| out1 <- val1[rep(NA_integer_, length(condition))] | |
| out2 <- val2[rep(NA_integer_, length(condition))] | |
| out1[condition & !is.na(condition)] <- val2[condition & !is.na(condition)] | |
| out2[condition & !is.na(condition)] <- val1[condition & !is.na(condition)] | |
| out1[!condition & !is.na(condition)] <- val1[!condition & !is.na(condition)] | |
| out2[!condition & !is.na(condition)] <- val2[!condition & !is.na(condition)] | |
| tibble(out1, out2) | |
| } | |
| #swaps, but want to use in a mutate call | |
| swap_if(dt$V2=="b", dt$V1, dt$V3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment