我有这个数据框架:
vehicles <- tibble(vehicle = c("Car", "Car", "Motorbike"),
color = c("Red", "Black", "Blue"),
speed = c("Low", "High", "High"))
与rlang::syms
:
library(dplyr)
choices = c("vehicle", "color", "speed")
vehicles %>%
mutate(category = paste(!!!rlang::syms(choices), sep = "_"))
输出# A tibble: 3 × 4
vehicle color speed category
<chr> <chr> <chr> <chr>
1 Car Red Low Car_Red_Low
2 Car Black High Car_Black_High
3 Motorbike Blue High Motorbike_Blue_High
使用unite
library(dplyr)
library(tidyr)
vehicles %>%
unite(category, all_of(choices), remove = FALSE) %>%
relocate(category, .after = last_col())
与产出
# A tibble: 3 × 4
vehicle color speed category
<chr> <chr> <chr> <chr>
1 Car Red Low Car_Red_Low
2 Car Black High Car_Black_High
3 Motorbike Blue High Motorbike_Blue_High