3
votes

I want to write a function which takes the log of all columns in a tibble:

test<-tibble(date=c("1992-01-01","1992-01-02"),
             value1=c(1,2),
             value2=c(3,4))

The difficulty for me is that I would like to append the logarithmic variable as a new column and the variable name should have the following form: e.g.: value_l. In dplyr this should be possible with mutate_all, but it seems that it is not possible to add a vector there.

test %>% 
  select(-"date") %>% 
  mutate_at(funs(!!paste0(colnames(test)[2],"_l") := log(.)))

My code gives me:

Error: The LHS of `:=` must be a string or a symbol
Call `rlang::last_error()` to see a backtrace.

Is there a way to bypass this and stay in the dplyr universe at the same time?

test<-tibble(date=c("1992-01-01","1992-01-02"),
             value1=c(1,2),
             value2=c(3,4),
             value1_l=log(c(1,2)),
             value2_l=log(c(3,4)))
3

3 Answers

4
votes

This is the way to do it using dplyr::mutate_at

  test %>%
    mutate_at(
      .vars = vars(contains("value")),
      .funs = list(l = ~log(.))
      )
2
votes

Here is a base R solution I use when faced with this problem:

test[paste0(names(test)[-1], "_log")] <- lapply(test[-1], log)

  date       value1 value2 value1_log value2_log
  <chr>       <dbl>  <dbl>      <dbl>      <dbl>
1 1992-01-01      1      3      0           1.10
2 1992-01-02      2      4      0.693       1.39
1
votes

Another tidyverse solution that generalises for more columns than just value1 and value2.

tibble(
  date=c("1992-01-01","1992-01-02"),
  value1=c(1,2),
  value2=c(3,4)
) %>% 
  mutate_at(vars(-date), funs(l = log(.)))