1

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?

6
  • 2
    Maybe this? stackoverflow.com/questions/32712301/… Commented Jun 16, 2019 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. Commented Jun 16, 2019 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) Commented Jun 16, 2019 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. Commented Jun 16, 2019 at 14:17
  • From the linked answer "To assign to variable(s), wrap the LHS of := in parentheses:" Commented Jun 16, 2019 at 22:18

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.