假设我有这个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呼叫,但得到了相同的输出

有没有人看到我做错了什么?

推荐答案

你需要的是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

R相关问答推荐

如何在列表的子元素上使用setName

R:对于没有数据的缓冲区,加权平均值为0

如何使用文本表达来子集数据

使用R的序列覆盖

从有序数据中随机抽样

更改Heatmap Annotation对象的名称

基于不同组的列的相关性

将年度数据插入月度数据

为什么观察不会被无功值变化触发?

删除具有相同标题的tabPanel(shinly)

使用整齐的计算(curl -curl )和杂音

对于变量的每个值,仅 Select 包含列表中所有值的值.R

如何在分组条形图中移动相关列?

如何基于两个条件从一列中提取行

展开对数比例绘图的轴(添加填充)

条形图顶部与其错误条形图不对齐

层次树图的数据树

有没有办法通过str_Detect()或其他字符串匹配函数来连接两个长度不等的数据帧?

Conditional documentr::R中数据帧的summarize()

替换在以前工作的代码中有x行&q;错误(geom_sf/gganimate/dow_mark)