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
!!!
withrename
on a named list or vector created fromvariable_labels
dataset-Check the names
Or if we want to use
rename_with
The reason
var_label
is not working is because it is looking for the value of the columns and not the column names i.e. according to?var_label
whereas
If we dig the function
rename_with.data.frame
it would be more evidenti.e. the
.fn
or 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