See the FAQ: How to do a minimal reproducible example reprex
for beginners for more specific guidance.
In general:
- Favor shorter, lower-case variable names for programming.
- When it comes time to output for presentation is when it makes sense to change over to longer, more highly formatted and descriptive names.
If the desired variable names follow no particular pattern, an effective way to change them is simply with colnames
.
colnames(mtcars)
#> [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
#> [11] "carb"
headers <- c("age","class","weight","iq","lipids","sugars","nacl","gender","grade","category","range")
colnames(mtcars) <- headers
head(mtcars)
#> age class weight iq lipids sugars nacl gender grade
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0
#> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0
#> category range
#> Mazda RX4 4 4
#> Mazda RX4 Wag 4 4
#> Datsun 710 4 1
#> Hornet 4 Drive 3 1
#> Hornet Sportabout 3 2
#> Valiant 3 1
If some transformation by function application of the colnames is desired, such as turning upper case to lower case, dplyr::rename
can be used as shown in the help for rename
If the new names represent a regular sequence, a function to generate them can be used to create the header
in the snippet above. For example, V_1 \dots V_n
colnames(mtcars) <- rep(paste0("V",1:11))
head(mtcars)
#> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Note that
colnames(mtcars) <- header
modifies mtcars
in place.