提问人:C.Robin 提问时间:8/7/2023 最后编辑:Darren TsaiC.Robin 更新时间:8/7/2023 访问量:31
str_replace内部fct_reorder内部突变(across())
str_replace inside fct_reorder inside mutate(across())
问:
假设我有这个小毛病:
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
)
我想制作以现有列名称的第一部分(减去或前缀)命名的新列,这些列采用列的值,但将它们转换为按相应列排序的因子。_txt
_num
_txt
_num
我可以通过对每列重复内部来做到这一点,如下所示:fct_reorder
mutate
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")))
但是,结果因子(how_bright
、how_hard
、how_hot
)的顺序不正确,与原始列中的顺序不对应。我也尝试过用呼叫替换呼叫,但我得到相同的输出_num
str_replace
gsub
谁能看到我做错了什么?
答:
1赞
Darren Tsai
8/7/2023
#1
你需要的是和. 给出当前列名,即 .After 在当前数据集中搜索新名称(即 )并返回其值。cur_column()
get()
cur_column()
*_txt
str_replace()
get()
*_num
library(tidyverse)
df %>%
mutate(across(ends_with("_txt"),
~ fct_reorder(.x, get(str_replace(cur_column(), "_txt", "_num"))),
.names = "{str_remove(.col, '_txt')}"),
.keep = "unused")
# # A tibble: 5 × 3
# how_bright how_hard how_hot
# <fct> <fct> <fct>
# 1 Not very much Really hard Cold
# 2 Somewhat Somewhat hard A bit cold
# 3 Medium Medium Medium
# 4 Quite a bit Quite hard Quite hot
# 5 A lot Not very hard Really hot
评论
0赞
C.Robin
8/7/2023
这行得通!谢谢。但是为什么?
1赞
Darren Tsai
8/7/2023
@C.Robin:我更新了一些描述。
评论