Search code examples
rdataframetibble

Is it possible to name a column of a tibble using a variable containing a character vector (string)?


Is there a way to name the column of a tibble using a variable? I want to name the first column below Clade for example. I tried paste() and assign(), but neither function seems to do what I want.

CLADE_FIELD = "Clade"
LINEAGE_FIELD = "Lineage"

  metaDF = tibble(CLADE_FIELD = c("G"), 
                       LINEAGE_FIELD = c("B.666"), 
                       "Submission date" = c("2020-03"))

I am using this code in a unit test which is why I am creating this tibble artificially. The name references a column name in a csv and I want the code to be easily maintainable if this column name changes.


Solution

  • 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