Advertisement
Guest User

Untitled

a guest
Sep 26th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. library(tidyverse)
  2.  
  3. dt <- tibble(V1=c(1,2,4), V2=c("a","a","b"), V3=c(2,3,1))
  4.  
  5. swap_if<- function (condition, val1, val2, missing = NA)
  6. {
  7. if (!is.logical(condition)) {
  8. stop("`condition` must be logical", call. = FALSE)
  9. }
  10. out1 <- val1[rep(NA_integer_, length(condition))]
  11. out2 <- val2[rep(NA_integer_, length(condition))]
  12.  
  13. out1[condition & !is.na(condition)] <- val2[condition & !is.na(condition)]
  14. out2[condition & !is.na(condition)] <- val1[condition & !is.na(condition)]
  15.  
  16. out1[!condition & !is.na(condition)] <- val1[!condition & !is.na(condition)]
  17. out2[!condition & !is.na(condition)] <- val2[!condition & !is.na(condition)]
  18.  
  19. tibble(out1, out2)
  20. }
  21.  
  22. #swaps, but want to use in a mutate call
  23. swap_if(dt$V2=="b", dt$V1, dt$V3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement