I am forever working with collaborators in SPSS and STata so clear variable labels are really important to communiate what has been done to any given variable and what it records.
How do I rename variables with their variable labels most efficiently in a tidyverse context. I can do this, but it seems very unwieldy.
var1<-rnorm(100)
var2<-rnorm(100)
var3<-rnorm(100)
group_var<-sample(c("A", "B"), size=100, replace=T)
other_var1<-rnorm(100)
other_var2<-rnorm(100)
df<-data.frame(var1, var2, var3, group_var, other_var1, other_var2)
library(labelled)
library(tidyverse)
df %>%
set_variable_labels(var1="Measure 1",
var2="Measure 2",
var3="Measure 3",
group_var="Grouping Variable")->df
#Store variable labels
df %>%
select(starts_with("var")) %>%
var_label() %>%
unlist()->variable_labels
variable_labels<-data.frame(name=names(variable_labels), labels=variable_labels)
df %>%
pivot_longer(var1:var3) %>%
left_join(., variable_labels, by="name")
Is there a way to make the rename_with function work here?
This does not do it.
df %>%
rename_with(., function(x) var_label(x),.cols=var1:var3)
We could use
!!!withrenameon a named list or vector created fromvariable_labelsdataset-Check the names
Or if we want to use
rename_withThe reason
var_labelis not working is because it is looking for the value of the columns and not the column names i.e. according to?var_labelwhereas
If we dig the function
rename_with.data.frameit would be more evidenti.e. the
.fnor the lambda function is applied on the column names. Thus, when we usevar_label, it require data.frame or vector and it fails-added print statements in a modified function
-Testing