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)