Say I want to create a data.table 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?
eval(parse(text = paste0("data.table(`", mycol, "`=1:5)")))
. Isn'tsetnames()
the way to go here? – sindri_baldur