bramtayl
bramtayl

Reputation: 4024

Create an update function

I would like to create an update function using lazy evaluation and the mutate_if function from dplyrExtras by skranz.

It would work something like this:

data %>%
  update(variable1_original = variable1_update,
         variable2_original = variable2_update)

would be evaluated as

data %>%
  mutate_if(!is.na(variable1_update), 
            variable1_original = variable1_update) %>%
  mutate_if(!is.na(variable2_update),
            variable2_original = variable2_update) %>%
  select(-variable1_update, variable2_update)

Upvotes: 0

Views: 156

Answers (1)

MrFlick
MrFlick

Reputation: 206232

Yikes, that package isn't very fun to use. mutate_if doesn't seem to work with data.frames and the package doesn't have standard-evaluation alternatives for functions like standard dplyr does. Here's an attempt to re-create the function

myupdate <- function(.data, ...) {
    dots <- as.list(substitute(...()))
    dx <- Reduce(function(a,b) {
        upd <- b[[1]]
        ifc <- bquote(!is.na(.(upd)))
        do.call("mutate_if", c(list(a, ifc), b))
    }, split(dots, seq_along(dots)), .data)
    select_(dx, .dots=sapply(dots, function(x) bquote(-.(x))))
}

To test it, i used

library(data.table)
dd<-data.table(
   a = c(1:3, NA, 5:8)+0,
   b = c(1:2, NA, 4:5, NA, 7:8)+100,
   x= 1:8+20,
   y=1:8+30
)
dd
#     a   b  x  y
# 1:  1 101 21 31
# 2:  2 102 22 32
# 3:  3  NA 23 33
# 4: NA 104 24 34
# 5:  5 105 25 35
# 6:  6  NA 26 36
# 7:  7 107 27 37
# 8:  8 108 28 38

and then I ran

myupdate(dd, x=b, y=a)
#      x  y
# 1: 101  1
# 2: 102  2
# 3:  23  3
# 4: 104 34
# 5: 105  5
# 6:  26  6
# 7: 107  7
# 8: 108  8

Notice how columns "a" and "b" disappear. Also see how values in rows 3 and 6 in column "x" and the value in row 4 in column "y" was preserved because the corresponding values in columns "b" and "a" were NA.

Upvotes: 1

Related Questions