A one-liner using mtcars
:
do.call(apply_labels, c(list(data=mtcars),setNames(names(mtcars), names(mtcars)) %>% as.list()))
However, for your use case, you can create a small function as below that takes a dataframe and a vector of new names, and basically moves the current column names to labels, and replaces the original (i.e. too long) names with the new names
replace_long_with_short <- function(d,short_names) {
setNames(
do.call(apply_labels, c(list(data=d),setNames(names(df), names(df)) %>% as.list())),
short_names
)
}
Pass your dataframe to this function, along with desired new names. The function will return the frame with the original column names as labels, and the new colnames will be the desired new names:
Example: Let's say you have a data frame that looks like this:
X.is.an.important.variable Y.is.also.important
1 -0.003643385 1.1052905
2 1.641458152 0.5303247
3 -1.058337452 0.5490569
and you want those descriptive column names to be the labels, and the new names to be x
and y
.
Then calling the above function like this:
df = replace_long_with_short(df,c("x", "y"))
will convert df
to this:
x y
1 -0.003643385 1.1052905
2 1.641458152 0.5303247
3 -1.058337452 0.5490569
and the labels will be attached:
str(df)
'data.frame': 3 obs. of 2 variables:
$ x:Class 'labelled' num -0.00364 1.64146 -1.05834
.. .. LABEL: X.is.an.important.variable
$ y:Class 'labelled' num 1.105 0.53 0.549
.. .. LABEL: Y.is.also.important