What is best practice for referencing to the value of another object outside that that function list()

Viewed 28

I have been avoiding the issue of understanding this problem for years, but I am getting to a experience level where I need to be able to write something like this and make it work. I think I have been told it has to do with evaluation and scope.

   ICD10 <- paste("^", c("DF17", "DZ720", paste("DJ", seq(40,44,1), sep = ""), "D716"), sep ="")
  ICD8 <- c()
  ATC <- c("^R03", "^N07BA")
 variableName <- c("smokingMarker")
 
VariableDefinor <- list( variableName = 
                list(ICD10 = ICD10, 
                      ICD8 = ICD8, 
                      ATC = ATC) 
)

Basicly the above code runs and creates a list called VariableDefinor. But the list inside has the name variableName rather than "smokingMarker". I think I can see what goes wrong, but I can't figure out how to fix this. I have looked into functions like paste do.call and as.name but I can't figure it out. It seems like there is something really basic that I just don't understand. I would greatly appreciate both help in solving this, and some reference to where I can learn about what it is I am not getting.

2 Answers

One option is := with dplyr::lst

dplyr::lst(!! variableName :=  dplyr::lst(ICD10, ICD8, ATC))

-output

#$smokingMarker
#$smokingMarker$ICD10
#[1] "^DF17"  "^DZ720" "^DJ40"  "^DJ41"  "^DJ42"  "^DJ43"  "^DJ44"  "^D716" 

#$smokingMarker$ICD8
#NULL

#$smokingMarker$ATC
#[1] "^R03"   "^N07BA"

In base R, this can also be done with setNames

setNames(list(list(ICD10 = ICD10,
           ICD8 = ICD8,
           ATC = ATC)), variableName)

Use mget to form the inner list and setNames/list to form the outer one. No packages are used.

setNames(list(mget(c("ICD10", "ICD8", "ATC"))), variableName)
Related