假设我有这个Tibble:
df <- tibble::tribble(
~how_bright_txt, ~how_bright_num, ~how_hard_txt, ~how_hard_num, ~how_hot_txt, ~how_hot_num,
"Not very much", 1L, "Really hard", 5L, "Cold", 1L,
"Somewhat", 2L, "Somewhat hard", 2L, "A bit cold", 2L,
"Medium", 3L, "Medium", 3L, "Medium", 3L,
"Quite a bit", 4L, "Quite hard", 4L, "Quite hot", 4L,
"A lot", 5L, "Not very hard", 1L, "Really hot", 5L
)
我想用现有列名的第一部分(减go _txt
或_num
前缀)命名新列,这些列采用_txt
列的值,但将它们转换为按相应_num
列排序的系数.
我可以通过对每列重复mutate
内的fct_reorder
来实现这一点,如下所示:
require(tidyverse)
df %>%
mutate(how_bright = fct_reorder(how_bright_txt, -how_bright_num),
how_hard = fct_reorder(how_hard_txt, -how_hard_num),
how_hot = fct_reorder(how_hot_txt, -how_hot_num)) %>%
select(-c(ends_with("_txt"), ends_with("_num")))
但我想简化这一点,使用mutate(across())
.所以我试着这么做:
df %>%
mutate(across(ends_with("_txt"),
~ fct_reorder(.x, str_replace(.x, "_txt", "_num")),
.names = '{stringr::str_remove({col}, "_txt")}')) %>%
select(-c(ends_with("_txt"), ends_with("_num")))
而是the ordering of the resulting factors (100, 101, 102) are incorrect,与最初_num
列中的顺序不符.我还try 将str_replace
呼叫替换为gsub
呼叫,但得到了相同的输出
有没有人看到我做错了什么?