-1

I have a data frame with 383 variables. Because the names of the variables are long and self-explanatory, I would like to add these names to the labels of variables, then in a second step (already successfully done), I would rename variables for easier coding. I have tried the following with the error:

library(expss)

REGCON_CA_FIRM <- apply_labels(REGCON_CA_FIRM,names(REGCON_CA_FIRM)<-names(REGCON_CA_FIRM))

# Error in if (curr_name %in% data_names) { : argument is of length zero
zephryl
  • 14,633
  • 3
  • 11
  • 30
  • 1
    Please provide some sample data via `dput()`. – Ed_Gravy Nov 18 '22 at 14:11
  • data("mtcars") will do the trick, I just want to add the names of the variables as labels of the variable. Let me know if that is ok. – Rubén Pérez Sanz Nov 18 '22 at 14:17
  • Can you add the desired output in your post for further clarification, thank you. – Ed_Gravy Nov 18 '22 at 14:20
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 18 '22 at 14:36
  • I assumed you’re using expss? If not, please [edit] your post with the correct package, as `apply_labels()` isn’t a base R function. – zephryl Nov 18 '22 at 14:49

1 Answers1

3

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 
langtang
  • 22,248
  • 1
  • 12
  • 27