Change from mutate_at() to mutate(across()) problem with function

Viewed 963

I'm trying to update my code for reverse coding items in a tibble to use the across() function in dplyr instead of mutate_at(). My present code looks like this:

reversed_items <- c("x1","x4","x12") 

data <- data %>% 
  mutate_at(vars(reversed_items), function(x)6-x )

This works. However, whenever I try to update my code to include the across() function I get this error:

Error: Problem with `mutate()` input `..2`.
x Input `..2` must be a vector, not a `formula` object.
ℹ Input `..2` is `~recode(6 - .x)`.

I've read: https://www.tidyverse.org/blog/2020/04/dplyr-1-0-0-colwise/ But can't get it to work.

1 Answers

Works fine, did you place the closing parenthesis in right spot for across:

data <- data.frame(c1 = round(rnorm(5)),
                   c2 = round(rnorm(5)),
                   c3 = round(rnorm(5)))
data
  c1 c2 c3
1 -1 -2  0
2  1 -1  1
3  2  1  1
4  0  0  0
5  1  0  2
reversed_items <- c("c1","c2","c3") 
data %>% mutate_at(vars(reversed_items), function(x)6-x )
  c1 c2 c3
1  7  8  6
2  5  7  5
3  4  5  5
4  6  6  6
5  5  6  4
data %>% mutate(across(reversed_items, function(x)6-x ))
  c1 c2 c3
1  7  8  6
2  5  7  5
3  4  5  5
4  6  6  6
5  5  6  4

Data used:

structure(list(c1 = c(-1, 1, 2, 0, 1), c2 = c(-2, -1, 1, 0, 0
), c3 = c(0, 1, 1, 0, 2)), class = "data.frame", row.names = c(NA, 
-5L))
Related