hjw
hjw

Reputation: 1289

mutate_at is not applied to all columns selected

I am trying to subtract one column from all others but not all columns are modified.

test <- tibble(a = 1:3, b = 2:4, c = 3:5, d = 4:6, e = 5:7)

col = 'd'
test %>% mutate_at(vars(-a), funs(. - !!as.name(col)))

      a     b     c     d     e
  <int> <int> <int> <int> <int>
1     1    -2    -1     0     5
2     2    -2    -1     0     6
3     3    -2    -1     0     7

I am not sure why the function isn't applied to column e. Function seems to be applied only up to the column I am using to subtract

col = 'b'
test %>% mutate_at(vars(-a), funs(. - !!as.name(col)))

  a     b     c     d     e
  <int> <int> <int> <int> <int>
1     1     0     3     4     5
2     2     0     4     5     6
3     3     0     5     6     7

I get the same behaviour when I use 'list' instead of 'funs' (although i haven't managed to figure out how to use dynamic variable name in 'list')

test %>% mutate_at(vars(-a), list(~. - b))
  a     b     c     d     e
  <int> <int> <int> <int> <int>
1     1     0     3     4     5
2     2     0     4     5     6
3     3     0     5     6     7

Let me know if I am doing anythiing wrong here.

Upvotes: 3

Views: 336

Answers (2)

d.b
d.b

Reputation: 32558

col = 'd'
test %>%
    mutate(temp = !!as.name(col)) %>%
    mutate_all(funs(. - temp)) %>%
    select(-temp)

Upvotes: 0

AndS.
AndS.

Reputation: 8120

I think the best way to do this is to pull the values you want first, then apply the subtraction.

library(tidyverse)

col = 'd'
vals <- pull(test, {{col}})

test %>% mutate_at(vars(-a), list(~.-vals))
#> # A tibble: 3 x 5
#>       a     b     c     d     e
#>   <int> <int> <int> <int> <int>
#> 1     1    -2    -1     0     1
#> 2     2    -2    -1     0     1
#> 3     3    -2    -1     0     1

Upvotes: 3

Related Questions