Skip to content
Prev 386894 / 398502 Next

writing a function to work with dplyr::mutate()

Your translate... function seems unnecessarily complicated and reusing the
name 'var' for both the input and the data.frame containing the input makes
it confusing to me.  The following replacement, f, uses your algorithm but
I think gets the answer you want.

f <-
function(var, upper, lookup) {
    names(lookup) <- c('old','new')
    var_df <- data.frame(old = var)
    lookup2 <- data.frame(old = c(1:upper),
                          new = c(1:upper))
    lookup3 <- rbind(lookup, lookup2)
    res <- left_join(var_df, lookup3, by = 'old')
    res$new # return a vector, not a data.frame or tibble.
}
E.g.,
f(YYY, 90, lup))
  XXX YYY YYY_mm
1  95  55     55
2  93  66     66
3  10  93      3
4  20  98     NA

You can modify this so that it names the output column based on the name of
the input column (by returning a data.frame/tibble instead of a numeric
vector):

f1 <-
function(var, upper, lookup,  new_varname =
paste0(deparse1(substitute(var)), "_mm")) {
    names(lookup) <- c('old',new_varname)
    var_df <- data.frame(old = var)
    lookup2 <- data.frame(old = c(1:upper),
                          new = c(1:upper))
    names(lookup2)[2] <- new_varname
    lookup3 <- rbind(lookup, lookup2)
    res <- left_join(var_df, lookup3, by = 'old')[2]
    res
}
E.g.,
90, lup))
  XXX YYY YYY_mm
1  95  55     55
2  93  66     66
3  10  93      3
4  20  98     NA

-Bill
On Tue, Jan 19, 2021 at 10:24 AM Steven Rigatti <sjrigatti at gmail.com> wrote: