【问题标题】:Change from mutate_at() to mutate(across()) problem with function从 mutate_at() 更改为 mutate(across()) 函数问题
【发布时间】:2020-11-07 09:15:00
【问题描述】:

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

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

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

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

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

我已阅读:https://www.tidyverse.org/blog/2020/04/dplyr-1-0-0-colwise/ 但无法正常工作。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

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

    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
    

    使用的数据:

    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))
    

    【讨论】:

    • 谢谢。好像我忘记了最后一个右括号..
    猜你喜欢
    • 2021-01-11
    • 2021-03-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多