r - 在跨函数的 .names 参数中使用函数
问题描述
在这个示例数据集中,我希望能够操纵.names
第二mutate(across...
部分中的参数:
特别是我想{.col}
使用类似sub
.
本质上:我想删除greater4
最后两列中的字符串:
Sepal.Length_greater4_greater50
并Sepal.Width_greater4_greater50
_
Sepal.Length_greater50
和Sepal.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
解决方案
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
推荐阅读
- python - 通过匹配来自另一个 Pandas 系列的多列索引来更新和求和 Pandas DataFrame
- javascript - Div 没有使用 jquery 关键帧围绕其中心旋转
- logging - Best way to find out which log statements are generating the most log volume?
- java - Strange output when float value is assigned to a double in JAVA. Getting weird decimals
- angular - Dynamically load data / load data from reference (dynamic filtering)
- reactjs - How do i create a conditional loading message in react
- groovy - how to call a groovy function in an active choice parameter in Jenkins pipeline
- php - How to check if both query excecuted successfully?
- ios - NSURLSession Error Domain=NSPOSIXErrorDomain Code=28 "No space left on device"
- openlayers - Openlayers - ArcGIS Vector tiles - OFFSET