Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement