0

The only way I know so far is in two steps: creating the columns with dummy names and then using setnames(). I would like to do it in one step, probably there is some parameter/option, but am not able to find it

# the awkward way I have found so far
col_names <- c("one", "two","three")
dt <- data.table()
# add columns with dummy names...
setnames(dt, col_names )

Also interested in a way to be able to use a variable with :=, something like

colNameVar <- "dummy_values"
DT[ , colNameVar := 1:10]

This question to me does not seem a duplicate of Select / assign to data.table when variable names are stored in a character vector here I ask about when creating a data.table, word "creating" in the title. This is totally different from when the data table is already created, which is the subject of the question indicated as duplicate, for the latter there are kown ways clearly documented, that do not work in the case I ask about here.

PS. Note similar question indicated in comment by @ Ronak Shah: Create empty data frame with column names by assigning a string vector?

user778806
  • 67
  • 6
  • 2
    Maybe this? https://stackoverflow.com/questions/32712301/create-empty-data-frame-with-column-names-by-assigning-a-string-vector/ – Ronak Shah Jun 16 '19 at 14:00
  • It seems identical to "my" way that I hope is improveable. Like me they create the data structure then, in a second step, assign the names to it. I was hoping there is a way to do everything in one step, though I cannot find it. – user778806 Jun 16 '19 at 14:07
  • 1
    I mean it has a one-liner in the end which would be `setNames(data.table(matrix(ncol = 3, nrow = 0)), col_names)` – Ronak Shah Jun 16 '19 at 14:11
  • Yes thanks, but what I am looking for is something like ..colNameVar or with = F that you can do once you have the DT. – user778806 Jun 16 '19 at 14:17
  • From the linked answer "To assign to variable(s), wrap the LHS of := in parentheses:" – Frank Jun 16 '19 at 22:18
  • @Frank did not work for me with DT = data.table(), which is the case I ask about, it works when the data.table already exists, which I do not ask about, except for the secondary question about := – user778806 Jun 17 '19 at 05:04

1 Answers1

1

For the first question, I'm not absolutely sure, but you may want to try and see if fread is of any help creating an empty data.table with named columns.

As for the second question, try

DT[, c(nameOfCols) := 10]

Where nameOfCols is the vector with names of the columns you want to modify. See ?data.table

PavoDive
  • 6,322
  • 2
  • 29
  • 55