I have a messy dataset that is like this:
Q1 <- "Age"
Q2 <- "Sex"
Q3 <- "Age"
Q4 <- "Race"
df <- data.frame(Q1,Q2,Q3,Q4)
How do I turn every value of row 1 into variable label? i.e: into something like this:
library(labelled)
var_label(df$Q1) <- "Age"
var_label(df$Q2) <- "Sex"
var_label(df$Q3) <- "Age"
var_label(df$Q4) <- "Race"
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!!!
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"