使用 mutate 对最后一列执行操作

bos*_*hek 5 r dplyr

有没有什么方法可以引用 mutate 中的最后一列,以便您可以对其进行操作?例如:

\n
library(dplyr)\nlibrary(tidyr)\ndat <- data.frame(\n  col1 = c(1, 1, 1),\n  col2 = c(0, 1, 0),\n  col3 = c(2, 0, 2)\n)\n\n## what i was thinking:\ndat %>%\n  mutate(col1_bigger_than_col3 = col1 > last_col())\n#> Error in `mutate()`:\n#> ! Problem while computing `col1_bigger_than_col3 = col1 > last_col()`.\n#> Caused by error:\n#> ! `last_col()` must be used within a *selecting* function.\n#> \xe2\x84\xb9 See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.\n\n#> Backtrace:\n#>      \xe2\x96\x86\n#>   1. \xe2\x94\x9c\xe2\x94\x80dat %>% mutate(col1_bigger_than_col3 = col1 > last_col())\n#>   2. \xe2\x94\x9c\xe2\x94\x80dplyr::mutate(., col1_bigger_than_col3 = col1 > last_col())\n#>   3. \xe2\x94\x9c\xe2\x94\x80dplyr:::mutate.data.frame(., col1_bigger_than_col3 = col1 > last_col())\n#>   4. \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80dplyr:::mutate_cols(.data, dplyr_quosures(...), caller_env = caller_env())\n#>   5. \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80base::withCallingHandlers(...)\n#>   6. \xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80mask$eval_all_mutate(quo)\n#>   7. \xe2\x94\x94\xe2\x94\x80tidyselect::last_col()\n#>   8.   \xe2\x94\x9c\xe2\x94\x80vars %||% peek_vars(fn = "last_col")\n#>   9.   \xe2\x94\x94\xe2\x94\x80tidyselect::peek_vars(fn = "last_col")\n#>  10.     \xe2\x94\x94\xe2\x94\x80rlang::abort(msg, call = NULL)\n\n## output i want\ndat %>%\n  mutate(col1_bigger_than_col3 = col1 > col3)\n#>   col1 col2 col3 col1_bigger_than_col3\n#> 1    1    0    2                 FALSE\n#> 2    1    1    0                  TRUE\n#> 3    1    0    2                 FALSE\n
Run Code Online (Sandbox Code Playgroud)\n

akr*_*run 6

我们可以使用last_col()inselect或 inacross

library(dplyr)
dat %>% 
   mutate(col1_bigger_than_col3 = col1 > across(last_col())[[1]])
Run Code Online (Sandbox Code Playgroud)

-输出

  col1 col2 col3 col1_bigger_than_col3
1    1    0    2                 FALSE
2    1    1    0                  TRUE
3    1    0    2                 FALSE
Run Code Online (Sandbox Code Playgroud)

.names或者在里面进行计算后更新across

dat %>%
   mutate(across(last_col(), ~ col1 > .x,
     .names = "col1_bigger_than_{.col}"))
  col1 col2 col3 col1_bigger_than_col3
1    1    0    2                FALSE
2    1    1    0                 TRUE
3    1    0    2                FALSE
Run Code Online (Sandbox Code Playgroud)