从 mutate_at() 更改为 mutate(across()) 函数问题

AlH*_*lHe 2 r dplyr

我正在尝试更新 tibble 中反向编码项目的代码,以使用across()dplyr 中的函数而不是mutate_at(). 我现在的代码如下所示:

\n
reversed_items <- c("x1","x4","x12") \n\ndata <- data %>% \n  mutate_at(vars(reversed_items), function(x)6-x )\n
Run Code Online (Sandbox Code Playgroud)\n

这有效。但是,每当我尝试更新代码以包含该across()函数时,我都会收到此错误:

\n
Error: Problem with `mutate()` input `..2`.\nx Input `..2` must be a vector, not a `formula` object.\n\xe2\x84\xb9 Input `..2` is `~recode(6 - .x)`.\n
Run Code Online (Sandbox Code Playgroud)\n

我读过: https: //www.tidyverse.org/blog/2020/04/dplyr-1-0-0-colwise/但无法让它工作。

\n

Kar*_*k S 5

工作正常,您是否将右括号放在了正确的位置:

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
Run Code Online (Sandbox Code Playgroud)

使用的数据:

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))
Run Code Online (Sandbox Code Playgroud)