You can use the following solution:
- In order to have column names that are stored as string we make use of bang bang operator
!!
which forces the evaluation of it succeeding name
- We also need to use walrus
:=
instead of =
which are equivalent and prompts you to supply name (as is the case with our variable name) on it LHS (left hand side)
CLADE_FIELD = "Clade"
LINEAGE_FIELD = "Lineage"
metaDF = tibble(!!CLADE_FIELD := c("G"),
!!LINEAGE_FIELD := c("B.666"),
"Submission date" = c("2020-03"))
# A tibble: 1 x 3
Clade Lineage `Submission date`
<chr> <chr> <chr>
1 G B.666 2020-03
Or we can use double braces {{}}
as follows:
metaDF = tibble({{CLADE_FIELD}} := c("G"),
{{LINEAGE_FIELD}} := c("B.666"),
"Submission date" = c("2020-03"))
# A tibble: 1 x 3
Clade Lineage `Submission date`
<chr> <chr> <chr>
1 G B.666 2020-03
Or we can make use of glue
syntax and put the variable name within a pair of braces {}
and pass the result as a string. Since glue syntax became available on the LHS of :=
whatever object (here your variable names) you put within a curly braces will be evaluated as R code:
metaDF = tibble("{CLADE_FIELD}" := c("G"),
"{LINEAGE_FIELD}" := c("B.666"),
"Submission date" = c("2020-03"))
# A tibble: 1 x 3
Clade Lineage `Submission date`
<chr> <chr> <chr>
1 G B.666 2020-03