0

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))
zx8754
  • 52,746
  • 12
  • 114
  • 209
samrr_tr
  • 81
  • 8

1 Answers1

0

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

expss::var_lab(df$all)<- "All"
expss::var_lab(df$vs1)<- "version" 
expss::var_lab(df$am1)<- "AMP"
expss::var_lab(df$gear1)<- "Gear Type"
expss::var_lab(df$am1)<- "carb type"

You can then make lists of the things you want to query:

dfl2 <- list("all","vs1","am1","gear1")
dfl1 <- list("all","vs1","am1")
dfl3 <- list("all","vs1","carb1")

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:

lapply(dfl2,
   \(x) {df[x] |> var_lab()})

gives

[[1]]
[1] "All"

[[2]]
[1] "version"

[[3]]
[1] "carb type"

[[4]]
[1] "Gear Type"

If the list output is not required, the output from sapply() is more readable:

> sapply(dfl2, \(x) {df[x] |> var_lab()})
[1] "All"       "version"   "carb type" "Gear Type"
> sapply(dfl1, \(x) {df[x] |> var_lab()})
[1] "All"       "version"   "carb type"
> sapply(dfl3, \(x) {df[x] |> var_lab()})
[[1]]
[1] "All"

[[2]]
[1] "version"

[[3]]
NULL

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.

Paul Stafford Allen
  • 1,840
  • 1
  • 5
  • 16