While using dplyr rename function, I've been renaming a string of columns like so:
dataset %>%
rename(
new.name1 = column.name.1,
new.name2 = column.name.2,
etc.
)
After the first line, R stops suggesting column variables while I type them out, leaving me typing things like very.long.and.complicated.variable.name.1 completely by hand. I checked the Global Options > code > completion section and everything is checked on, automatic etc. I couldn't find any threads detailing my situation. Any ideas?
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.
This is great. Thanks so much for the help, very much appreciated!
1 Like
system
Closed
June 18, 2021, 9:22pm
4
This topic was automatically closed 21 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.