使用 purrr::map 根据模式重命名

Using purrr::map to rename based on a pattern

我有一个变量名模式,它对我来说是可区分的,但不是因为信息编码在变量名中。因此,我感兴趣的变量都以相同的随机字母数字废话开头,后跟一个与类型相关的 _Number 和一个 _time,所以它们看起来像 nonsense_#_#,转换为 Variable_Type_Time。类型范围从1:3和3个时间段1,5,7.

有没有一种方法可以使用 purrr:: 和某种正则表达式进行功能重命名,以避免一次重命名一次(asf_1_1 = `Var1 TypeA Time1`,asf_1_2 = `Var1 TypeA Time2`。等) PS。我打算使用反引号格式的变量名,但您不必为了这些建议而这样做。

问题的可重现代码

    x <- c("_1_1",
       "_1_2",
       "_1_3",
       "_2_1",
       "_2_2",
       "_2_3",
       "_3_1",
       "_3_2",
       "_3_3",
       "_4_3")
paste0("asf",x)

test <- t(as_tibble(rnorm(10, 5.5, .35)))
colnames(test) <- paste0("asf",x)

如果列的格式相同,即 "_1_1", "_1_2", "_1_3", "_2_1", "_2_2", "_2_3" 等,那么您可以使用 outer 生成列名。

Type <- 1:3
Time <- 1:3
colnames(test) <- paste('Var1', c(t(outer(paste0('Type', LETTERS[Type]), 
                        paste0('Time', Time), paste, sep = ' '))), sep = ' ')
test

#      Var1 TypeA Time1 Var1 TypeA Time2 Var1 TypeA Time3 Var1 TypeB Time1
#value         5.516318         5.772653         5.033264         5.858262
#      Var1 TypeB Time2 Var1 TypeB Time3 Var1 TypeC Time1 Var1 TypeC Time2
#value         5.370641         5.213774         5.270832          5.26579
#      Var1 TypeC Time3
#value          5.55312

对于这个例子,我从 x 中删除了 "_4_3" 值。

你的问题对我来说有点模棱两可;这是你想要做的吗?

library(tidyverse)
x <- c("_1_1",
       "_1_2",
       "_1_3",
       "_2_1",
       "_2_2",
       "_2_3",
       "_3_1",
       "_3_2",
       "_3_3",
       "_4_3")
paste0("asf",x)

test <- t(as_tibble(rnorm(10, 5.5, .35)))
colnames(test) <- paste0("asf",x)

test_renamed <- as.data.frame(test) %>% 
  rename_with(~ sub("asf", "Var1 ", .x)) %>%
  rename_with(~ sub(" _", " Type", .x)) %>% 
  rename_with(~ sub("_", " Time", .x))

colnames(test_renamed)
#> [1] "Var1 Type1 Time1" "Var1 Type1 Time2" "Var1 Type1 Time3" "Var1 Type2 Time1"
#>[5] "Var1 Type2 Time2" "Var1 Type2 Time3" "Var1 Type3 Time1" "Var1 Type3 Time2"
#>[9] "Var1 Type3 Time3" "Var1 Type4 Time3"

test_renamed$`Var1 Type1 Time1`
#>[1] 5.868449