首页 > 解决方案 > 在跨函数的 .names 参数中使用函数

问题描述

在这个示例数据集中,我希望能够操纵.names第二mutate(across...部分中的参数:

特别是我想{.col}使用类似sub.

本质上:我想删除greater4最后两列中的字符串:

Sepal.Length_greater4_greater50Sepal.Width_greater4_greater50_

Sepal.Length_greater50Sepal.Width_greater50

示例数据:

library(dplyr)
head(iris, 5) %>% 
  select(1,2) %>% 
  mutate(across(contains("Sepal"), ~ifelse(. > 4, 1, 0), .names = "{.col}_greater4")) %>% 
  mutate(across(contains("4"), ~ifelse(. < 50, 1, 0), .names = "{.col}_greater50"))

Sepal.Length Sepal.Width Sepal.Length_greater4 Sepal.Width_greater4 Sepal.Length_greater4_greater50 Sepal.Width_greater4_greater50
1          5.1         3.5                     1                    0                               1                              1
2          4.9         3.0                     1                    0                               1                              1
3          4.7         3.2                     1                    0                               1                              1
4          4.6         3.1                     1                    0                               1                              1
5          5.0         3.6                     1                    0                               1                              1

标签: rdplyracross

解决方案


str_replace内使用{}

library(stringr)
library(dplyr)
 head(iris, 5) %>% 
  select(1,2) %>% 
  mutate(across(contains("Sepal"), ~ifelse(. > 4, 1, 0), 
      .names = "{.col}_greater4")) %>% 
  mutate(across(contains("4"), ~ifelse(. < 50, 1, 0), 
    .names = "{str_replace(.col, '_greater4', '_greater50')}"))

-输出

  Sepal.Length Sepal.Width Sepal.Length_greater4 Sepal.Width_greater4 Sepal.Length_greater50 Sepal.Width_greater50
1          5.1         3.5                     1                    0                      1                     1
2          4.9         3.0                     1                    0                      1                     1
3          4.7         3.2                     1                    0                      1                     1
4          4.6         3.1                     1                    0                      1                     1
5          5.0         3.6                     1                    0                      1                     1

推荐阅读