I'm surprised to find no one asked this question on Stackoverflow before. Maybe it's too stupid to ask?
So I have a dataframe that contains 48 weather variables, each representing a weather value for a month. I have drawn a simplified table shown below:
weather 1 | weather 2 | weather 3 | weather 4 | weather 5 | weather 6 | weather 7 | weather 8 | weather 9 | weather 10 | weather 11 | weather 12 |
---|---|---|---|---|---|---|---|---|---|---|---|
12 | 6 | 34 | 9 | 100 | .01 | -4 | 38 | 64 | 77 | 21 | 34 |
99 | 42 | -3 | 34 | 34 | .5 | 27 | 19 | 7 | 18 | NA | 20 |
My objective is to make the column names from "weather 1, weather 2, ..." to "weather 01, weather 02, ...." And I wrote a loop like this:
for (i in 1:9){
colnames(df) = gsub(i, 0+i, colnames(df))
}
However, instead of replacing the single-digit numbers with a leading zero, R replaced the actual letter "i" with "0+i". Can anyone let me know what's going on here and how to fix it? Or is there a better way to add leading zeros to column names?
Thank you very much!
We can use
library(stringr)
colnames(df) <- str_replace(colnames(df), "\\d+",
function(x) sprintf("%02d", as.integer(x)))