i want to extract labels from the labelelled column from the database. so here i want to extract labels for lists dfl1, dfl2, dfl3 dynamically.
output can be a list of labels ("all","version","amp") for dfl1 and ("all","version","amp", "gear type") for dfl2 and so on.
i treid with sapply and tail but its fetching according to the length of list not exactly what are the columns in lists
library(expss)
df <- mtcars
df$vs<-factor(df$vs, levels=c(1,0), labels = c("version","others"))
df$am<-factor(df$am, levels=c(1,0), labels = c("AMP","others"))
df$gear<-factor(df$gear, levels=c(3,4,5), labels = c("3G","4G","5G"))
df$carb<-factor(df$carb, levels=c(1,2,3,4,6,8), labels = c("one","two","three","four","six","eight"))
df$all<- 1
df$vs1<-ifelse(df$vs=='version',1,NA)
df$am1<-ifelse(df$am == 'AMP', 1, NA)
df$gear1<-ifelse(df$gear == '4G', 1, NA)
df$carb1<-ifelse(df$carb == 'three', 1, NA)
expss::val_lab(df$all)<-c("All"=1)
expss::val_lab(df$vs1)<-c("version"=1)
expss::val_lab(df$am1)<-c("AMP"=1)
expss::val_lab(df$gear1)<-c("Gear Type"=1)
expss::val_lab(df$am1)<-c("carb type"=1)
dfl2 <- list(df$all,df$vs1,df$am1,df$gear1)
dfl1 <- list(df$all,df$vs1,df$am1)
dfl3 <- list(df$all,df$vs1,df$carb1)
listt = dfl1
d1 <- tail(sapply(df, function(x) names(val_lab(x))),length(listt))
If I've correctly understood your aim, I think you want to set variable labels (a label for the column, effectively) not value labels (the equivalent of factor level labels):
You can then make lists of the things you want to query:
Notice I've just used the column header names in string format - writing it your way (e.g.
dfl2 <- list(df$all,df$vs1,df$am1,df$gear1)means the list stores the contents of those columns too).You can then use
lapply()to query each entry in one of the lists:gives
If the list output is not required, the output from
sapply()is more readable:Note the last one gives NULL because you never defined a label for "carb1" - you define the label for "am1" twice - I assume this is a typo but have left it in for reproducibility.