Skip to content

Instantly share code, notes, and snippets.

@bhive01
Created September 26, 2016 21:04
Show Gist options
  • Select an option

  • Save bhive01/40e6296604cead0050e1f73384203cb8 to your computer and use it in GitHub Desktop.

Select an option

Save bhive01/40e6296604cead0050e1f73384203cb8 to your computer and use it in GitHub Desktop.
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