如何将多个 stringr 函数与 mutate 和 across 一起使用?
How can I use multiple stringr functions with mutate & across?
我想跨两个或多个指定的列进行变异,并使所有字符串小写,并在同一步骤中用下划线替换空格。
例如...
起始数据集
> tribble(
+ ~colA, ~colB,
+ "a b C", "De F",
+ "A c B", "d E f",
+ "A B C", "D Ef"
+ )
# A tibble: 3 × 2
colA colB
<chr> <chr>
1 a b C De F
2 A c B d E f
3 A B C D Ef
最终应该是这样的
# A tibble: 3 × 2
colA colB
<chr> <chr>
1 a_b_c de_f
2 a_c_b d_e_f
3 a_b_c d_ef
到目前为止我有
dat %>%
mutate(across(.cols = c(colA, colB), .fns = str_to_lower(str_replace(., " ", "_"))))
但是我收到以下错误信息
Error in `mutate()`:
! Problem while computing `..1 = across(...)`.
Caused by error in `across()`:
! `.fns` must be NULL, a function, a formula, or a list of functions/formulas.
Run `rlang::last_error()` to see where the error occurred.
Warning message:
Problem while computing `..1 = across(...)`.
ℹ argument is not an atomic vector; coercing
这是语法错误。使用 ~
指定 .fns
并使用 .
。此外,str_replace
只会替换第一个值,要替换所有值,请使用 str_replace_all
.
library(dplyr)
library(stringr)
dat %>%
mutate(across(.cols = c(colA, colB),
.fns = ~str_to_lower(str_replace_all(., " ", "_"))))
# A tibble: 3 × 2
# colA colB
# <chr> <chr>
#1 a_b_c de_f
#2 a_c_b d_e_f
#3 a_b_c d_ef
我想跨两个或多个指定的列进行变异,并使所有字符串小写,并在同一步骤中用下划线替换空格。
例如...
起始数据集
> tribble(
+ ~colA, ~colB,
+ "a b C", "De F",
+ "A c B", "d E f",
+ "A B C", "D Ef"
+ )
# A tibble: 3 × 2
colA colB
<chr> <chr>
1 a b C De F
2 A c B d E f
3 A B C D Ef
最终应该是这样的
# A tibble: 3 × 2
colA colB
<chr> <chr>
1 a_b_c de_f
2 a_c_b d_e_f
3 a_b_c d_ef
到目前为止我有
dat %>%
mutate(across(.cols = c(colA, colB), .fns = str_to_lower(str_replace(., " ", "_"))))
但是我收到以下错误信息
Error in `mutate()`:
! Problem while computing `..1 = across(...)`.
Caused by error in `across()`:
! `.fns` must be NULL, a function, a formula, or a list of functions/formulas.
Run `rlang::last_error()` to see where the error occurred.
Warning message:
Problem while computing `..1 = across(...)`.
ℹ argument is not an atomic vector; coercing
这是语法错误。使用 ~
指定 .fns
并使用 .
。此外,str_replace
只会替换第一个值,要替换所有值,请使用 str_replace_all
.
library(dplyr)
library(stringr)
dat %>%
mutate(across(.cols = c(colA, colB),
.fns = ~str_to_lower(str_replace_all(., " ", "_"))))
# A tibble: 3 × 2
# colA colB
# <chr> <chr>
#1 a_b_c de_f
#2 a_c_b d_e_f
#3 a_b_c d_ef