dplyrmutate_at并一起重命名

我经常遇到必须重新编码遵循相同结构的多个列并将它们保存到具有不同名称的列中的问题。如果我可以覆盖它们,这将只是其中的一行dplyr,但由于我也想保留原始列,我不知道一个好的解决方案。下图。

这将是我想要复制的输出的长代码:

library(dplyr)
library(ggplot2)
data("diamonds")

diamonds <- diamonds %>% 
  mutate(x_char = case_when(x <= 4.5 ~ "low",
                       x >  4.5 & x < 7 ~ "so-so",
                       x >= 7 ~ "large",
                       TRUE ~ as.character(NA)),
         y_char = case_when(y <= 4.5 ~ "low",
                            y >  4.5 & y < 7 ~ "so-so",
                            y >= 7 ~ "large",
                            TRUE ~ as.character(NA)),
         z_char = case_when(z <= 4.5 ~ "low",
                            z >  4.5 & z < 7 ~ "so-so",
                            z >= 7 ~ "large",
                            TRUE ~ as.character(NA)))

这将是覆盖原始列的 mutate_at 的简短代码:

library(dplyr)
library(ggplot2)
data("diamonds")

diamonds <- diamonds %>%
  mutate_at(vars(x, y, z), ~ case_when(. <= 4.5 ~ "low",
                                       . >  4.5 & . < 7 ~ "so-so",
                                       . >= 7 ~ "large",
                                       TRUE ~ as.character(NA)))

有没有办法用 mutate_at 保留短代码,但以保留原始列的方式更改它,并使用不同的名称保存新列?在示例中,这意味着_char在原始列名的末尾添加并根据嵌入的公式更改重新编码。

回答

尝试使用 across

library(tidyverse)

diamonds %>% 
  mutate(
    across(.cols = c(x, y, z),
           .fns = ~case_when(.x <= 4.5 ~ "low",
                             .x >  4.5 & x < 7 ~ "so-so",
                             .x >= 7 ~ "large",
                             TRUE ~ as.character(NA)),
           .names = "{.col}_char")
  )
#> # A tibble: 53,940 x 13
#>    carat cut     color clarity depth table price     x     y     z x_char y_char
#>    <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>  <chr> 
#>  1 0.23  Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43 low    low   
#>  2 0.21  Premium E     SI1      59.8    61   326  3.89  3.84  2.31 low    low   
#>  3 0.23  Good    E     VS1      56.9    65   327  4.05  4.07  2.31 low    low   
#>  4 0.290 Premium I     VS2      62.4    58   334  4.2   4.23  2.63 low    low   
#>  5 0.31  Good    J     SI2      63.3    58   335  4.34  4.35  2.75 low    low   
#>  6 0.24  Very G~ J     VVS2     62.8    57   336  3.94  3.96  2.48 low    low   
#>  7 0.24  Very G~ I     VVS1     62.3    57   336  3.95  3.98  2.47 low    low   
#>  8 0.26  Very G~ H     SI1      61.9    55   337  4.07  4.11  2.53 low    low   
#>  9 0.22  Fair    E     VS2      65.1    61   337  3.87  3.78  2.49 low    low   
#> 10 0.23  Very G~ H     VS1      59.4    61   338  4     4.05  2.39 low    low   
#> # ... with 53,930 more rows, and 1 more variable: z_char <chr>

由reprex 包(v1.0.0)于 2021 年 3 月 9 日创建


以上是dplyrmutate_at并一起重命名的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>