Home > Enterprise >  Renaming a segment of columns of a data frame
Renaming a segment of columns of a data frame

Time:08-27

I have got a data frame which holds 100 columns. Some of the columns have "Q001_" in their names, some "Q010_". Behind these segments there is a number. One column is called "CASE" without a number behind it. I want to rename only the "Q010_" segment and call it "Q001_" instead while keeping the number behind it. The CASE column's name shall not be changed.

This is my data:

>      names(Q1_IDAS)
  [1] "Q001_01" "Q001_02" "Q001_03" "Q001_04" "Q001_05" "Q001_06" "Q001_07" "Q001_08" "Q001_09" "Q001_10" "Q001_11" "Q001_12" "Q001_13" "Q001_14" "Q001_15" "Q001_16"
 [17] "Q001_17" "Q001_18" "Q001_19" "Q001_20" "Q001_21" "Q001_22" "Q001_23" "Q001_24" "Q001_25" "Q001_26" "Q001_27" "Q001_28" "Q001_29" "Q001_30" "Q001_31" "Q001_32"
 [33] "Q001_33" "Q001_34" "Q001_35" "Q001_36" "Q001_37" "Q001_38" "Q001_39" "Q001_40" "Q001_41" "Q001_42" "Q001_43" "Q001_44" "Q001_45" "Q001_46" "Q001_47" "Q001_48"
 [49] "Q001_49" "Q001_50" "Q001_51" "Q001_52" "Q001_53" "Q001_54" "Q001_55" "Q001_56" "Q001_57" "Q001_58" "Q001_59" "Q001_60" "Q001_61" "Q001_62" "Q001_63" "Q001_64"
 [65] "Q001_65" "Q001_66" "Q001_67" "Q001_68" "Q001_69" "Q010_70" "Q010_71" "Q010_72" "Q010_73" "Q010_74" "Q010_75" "Q010_76" "Q010_77" "Q010_78" "Q010_79" "Q010_80"
 [81] "Q010_81" "Q010_82" "Q010_83" "Q010_84" "Q010_85" "Q010_86" "Q010_87" "Q010_88" "Q010_89" "Q010_90" "Q010_91" "Q010_92" "Q010_93" "Q010_94" "Q010_95" "Q010_96"
 [97] "Q010_97" "Q010_98" "Q010_99" "CASE"   

CodePudding user response:

You could simply do

names(Q1_IDAS) <- gsub("Q010","Q001",names(Q1_IDAS))

CodePudding user response:

Dummy data frame:

# A tibble: 10 x 5
   Q001_01 Q001_02 Q010_05  CASE Q010_10
     <int>   <int>   <int> <int>   <int>
 1       3       1       8     4       8
 2       8       5       5     5       2
 3       4       8       4     2       7
 4       6       6       6    10      10
 5       2       3       1     3       1
 6      10      10       9     1       3
 7       5       2      10     6       4
 8       7       4       7     8       5
 9       9       9       3     9       6
10       1       7       2     7       9

Renaming:

df %>%
  rename_with(., ~ str_replace_all(.x,
                                   pattern = "Q010", replacement = "Q001"))


# A tibble: 10 x 5
   Q001_01 Q001_02 Q001_05  CASE Q001_10
     <int>   <int>   <int> <int>   <int>
 1       5       1       4     8       1
 2       9       5       7     9      10
 3       8       2       6    10       7
 4      10       7       9     2       5
 5       3       9       5     4       6
 6       1       6       8     3       9
 7       2       8       3     1       8
 8       6      10       2     7       2
 9       7       4       1     6       4
10       4       3      10     5       3
  • Related