Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turn row values into variable labels

I have a messy dataset that is like this:

Q1 <- "Age"
Q2 <- "Sex"
Q3 <- "Age"
Q4 <- "Race"
df <- data.frame(Q1,Q2,Q3,Q4)

enter image description here

How do I turn every value of row 1 into variable label?
i.e: into something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(labelled)
var_label(df$Q1) <- "Age"
var_label(df$Q2) <- "Sex"
var_label(df$Q3) <- "Age"
var_label(df$Q4) <- "Race"

enter image description here

I have a large dataset with many variables. Is there a faster and efficient way to do this? How do I turn every value of row 1 into variable label?

I would appreciate all the help there is! Thanks!!!

>Solution :

The var_label can take a vector of data.frame as input, so, we can use

var_label(df) <- df[1, , drop = FALSE]

-output

> str(df)
'data.frame':   1 obs. of  4 variables:
 $ Q1: chr "Age"
  ..- attr(*, "label")= chr "Age"
 $ Q2: chr "Sex"
  ..- attr(*, "label")= chr "Sex"
 $ Q3: chr "Age"
  ..- attr(*, "label")= chr "Age"
 $ Q4: chr "Race"
  ..- attr(*, "label")= chr "Race"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading