spindoctor
spindoctor

Reputation: 1895

Is there a way to assign parts of the variable labels to be the variable name in R

Is there a way that I can grab parts of the variable label in a data frame and use that for the name of the variable? Something like this below works manually, but I'm wondering if there's a more automatic way to do this. Thank you.

library(tidyverse)
library(labelled)

var1<-labelled(sample(c(0,1), replace=T, size=100), c(selected=1, `Not Selected`=0), label="Alpha Beta Omega")
var2<-labelled(sample(c(0,1), replace=T, size=100), c(selected=1, `Not Selected`=0), label="Delta Kappa Gamma")
df<-data.frame(var1, var2)

var_label(df$var1)
val_labels(df$var1)

df %>% 
  rename(Beta=var1, Kappa=var2)

Upvotes: 1

Views: 133

Answers (2)

akrun
akrun

Reputation: 886968

Using word

library(dplyr)
library(stringr)
tmp <- stack(var_label(df)) %>% 
     mutate(values = word(values, 2)) 
df <- df %>%
     rename_with(~ tmp$values, everything())

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

Extract the part of the label using regex and assign it to the name.

library(labelled)
names(df) <- sub('\\w+\\s(\\w+)\\s\\w+', '\\1', unlist(var_label(df)))
df

where

sub('\\w+\\s(\\w+)\\s\\w+', '\\1', unlist(var_label(df))) #returns
#   Beta   Kappa 
#  "Beta" "Kappa" 

Upvotes: 1

Related Questions