Renaming columns with the same names in dataframe

I have got following columns' names:

"P18" "P18" "P19" "P19" "P20" "P20" "P21" "P21" "P22" "P22" "P23" "P23"

I would like to rename these columns by adding to first column "correlation" and to the second "p-value", in order to my columns'names look like this"
P18_correlation, P18_p_value and so on. How do I do it, please ?

You can build the names you want with paste() and assign them to the data frame with colnames().

NMs <- c("P18", "P18","P19", "P19", "P20", "P20", "P21", "P21", 
         "P22", "P22", "P23", "P23")
NMs <- paste(NMs, c("corr", "p_value"),sep="_")
 [1] "P18_corr"    "P18_p_value" "P19_corr"    "P19_p_value" "P20_corr"   
 [6] "P20_p_value" "P21_corr"    "P21_p_value" "P22_corr"    "P22_p_value"
[11] "P23_corr"    "P23_p_value"

Is it still the same when my dataframe is called "all" ?

 [1] "P18" "P18" "P19" "P19" "P20" "P20" "P21" "P21" "P22" "P22" "P23" "P23"

Thank you for your kind reply.

DF <- data.frame(A=1,B=2,C=3,D=4,E=5,F=6,G=7,H=8,I=9,J=10,K=11,L=12)
#>   A B C D E F G H I  J  K  L
#> 1 1 2 3 4 5 6 7 8 9 10 11 12
NMs <- c("P18", "P18","P19", "P19", "P20", "P20", "P21", "P21", 
         "P22", "P22", "P23", "P23")
NMs <- paste(NMs,c("corr","p_value"),sep="_")

colnames(DF) <- NMs
#>   P18_corr P18_p_value P19_corr P19_p_value P20_corr P20_p_value P21_corr
#> 1        1           2        3           4        5           6        7
#>   P21_p_value P22_corr P22_p_value P23_corr P23_p_value
#> 1           8        9          10       11          12

Created on 2022-02-05 by the reprex package (v2.0.1)

Thank you very much indeed for your solution.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.