2

Let's say I need to do this:

foo <- list(`a+b` = 5)

but I have 'a+b' (a string) saved in a variable, let's say name:

name <- 'a+b'

How to create that list with an element whose name is the value in the variable name?

Note: I am aware of other ways of assigning names to elements of lists. The list here is just an example. What I want to understand is how I deal with non-standard evaluation so that I can indicate to a function the named argument without having to type it directly inline.

I have read Hadley's Advanced R Chapter 13 on Non-standard evaluation but I am lost on how to do this still.

Any solution with base R or Tidy Evaluation is appreciated.

Ramiro Magno
  • 3,085
  • 15
  • 30

1 Answers1

3

We can use setNames

bar <- setNames(list(5), name)
identical(foo, bar)
#[1] TRUE

Or create the object first and then use names

bar2 <- list(5)
names(bar2) <- name

or with names<-

bar3 <- `names<-`(list(5), name)

Also, the tidyverse option would be to unquote (!!) and assign (:=)

library(tidyverse)
lst(!! name := 5)
#$`a+b`
#[1] 5
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Thank you for your quick reply. The first three methods, resulting in `bar`, `bar2` and `bar3` are a bit of workarounds... Is there no way in base R to still use `list()`? Regarding the `tidyverse` solution, is `lst` an exported function from `tidyverse`? – Ramiro Magno Feb 15 '19 at 12:02
  • 1
    @rmagno `lst` is from `tibble`, which is one package in tidyverse. `setNames` in `base R` is the easiest option in `base R`. – akrun Feb 15 '19 at 12:03
  • 1
    `purrr::lst`: `Error: 'lst' is not an exported object from 'namespace:purrr'`. My purrr package version is 0.3.0. – Ramiro Magno Feb 15 '19 at 12:08
  • 1
    @rmagno. I edited the earlier comment. It is from `tibble` – akrun Feb 15 '19 at 12:09
  • Yes, the last option is fine, I was just trying to understand how to do it with non-standard evaluation in base R... – Ramiro Magno Feb 15 '19 at 12:09
  • 2
    There were 2 goals with this question: the pratical one of getting it done: your solution with tidyverse is just fine. Now, I also wanted to understand if it is possible to refer to a named argument by the value of a variable. But your answer is just fine. – Ramiro Magno Feb 15 '19 at 12:12