Extract labels dynamically from database

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

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$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$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))

I'm not sure I understand. What you want is the equivalent of this?

d1 <- sapply(df, function(x) names(val_lab(x)))[c("all", "vs1", "am1")]
#> $all
#> [1] "All"
#> $vs1
#> [1] "version"
#> $am1
#> [1] "carb type"

but where the name vector is automatically created from listt?

That doesn't seem possible: dfl1 is an unnamed list, so the names of the columns used to create it are not saved in it. If you want to create it as a named list you can do:

dfl1 <- list(all = df$all, vs1 = df$vs1, am1 = df$am1)

d1 <- sapply(df, function(x) names(val_lab(x)))[names(dfl1)]

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.