0
votes

Say I want to create a with a column whose name is specified in a string. I can do it like so:

# Load library  
library(data.table)

# Name for my column
mycol <- "Column Name"

# Create data table
dt <- data.table(1:5)

# Peek
dt
#>    V1
#> 1:  1
#> 2:  2
#> 3:  3
#> 4:  4
#> 5:  5

# Rename
names(dt) <- mycol

# Peek
dt
#>    Column Name
#> 1:           1
#> 2:           2
#> 3:           3
#> 4:           4
#> 5:           5

Created on 2020-01-30 by the reprex package (v0.3.0)

My question is, can I make this more concise by using the string in the constructor? Something like dt <- data.table(eval(mycol) = 1:5) (which doesn't work).

I'm aware of this answer, which explains several ways to add variables whose names are strings to existing data tables, but this doesn't explain how to do this in data.table's constructor. Is it possible?

1
Not pretty and not more concise but eval(parse(text = paste0("data.table(`", mycol, "`=1:5)"))). Isn't setnames() the way to go here?sindri_baldur

1 Answers

0
votes

Maybe using setnames() like so:

dt <- setnames(data.table(1:5), mycol)

or

dt <- data.table(1:5)
setnames(dt, mycol) # Update by reference