sbac
sbac

Reputation: 2081

How to mutate a variable in a tibble based on columns named as numbers in R

I have a tibble with columns named as numbers (e.g. 1). I created a function to compute differences between columns, but I don't know how to do it with that type of columns:

<!-- language-all: lang-r -->


    library(tidyverse)
    df <- tibble(`1` = c(1,2,3), `2` = c(2,4,6))

    # This works
    df %>%
      mutate(diff = `1` - `2`) 
    #> # A tibble: 3 x 3
    #>     `1`   `2`  diff
    #>   <dbl> <dbl> <dbl>
    #> 1     1     2    -1
    #> 2     2     4    -2
    #> 3     3     6    -3

    # But this doesn't
    calc_diffs <- function(x, y){
      df %>%
        mutate(diff := !!x - !!y)
    }

    calc_diffs(1, 2)
    #> # A tibble: 3 x 3
    #>     `1`   `2`  diff
    #>   <dbl> <dbl> <dbl>
    #> 1     1     2    -1
    #> 2     2     4    -1
    #> 3     3     6    -1

<sup>Created on 2020-10-14 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>

Upvotes: 1

Views: 137

Answers (2)

Karthik S
Karthik S

Reputation: 11546

Does this work:

> df <- tibble(`1` = c(1,2,3), `2` = c(2,4,6))
> df
# A tibble: 3 x 2
    `1`   `2`
  <dbl> <dbl>
1     1     2
2     2     4
3     3     6
> calc_diffs <- function(x, y){
+   df %>%
+     mutate(diff = {{x}} - {{y}})
+ }
> calc_diffs(`1`,`2`)
# A tibble: 3 x 3
    `1`   `2`  diff
  <dbl> <dbl> <dbl>
1     1     2    -1
2     2     4    -2
3     3     6    -3
> 

Upvotes: 2

akrun
akrun

Reputation: 887891

We can convert to a symbol and evaluate

calc_diffs <- function(x, y){
  df %>%
    mutate(diff := !! rlang::sym(x) - !!rlang::sym(y))
}

Then, we just pass a string as argument

calc_diffs("1", "2")
# A tibble: 3 x 3
#    `1`   `2`  diff
#  <dbl> <dbl> <dbl>
#1     1     2    -1
#2     2     4    -2
#3     3     6    -3

Column names are strings. We could pass index to subset the column, but here the column name is an unusual name that starts with number. So, either we can wrap it with backreference using paste or just pass a string, convert to symbol and evaluate (!!)

Upvotes: 2

Related Questions