5

i want to create a data.table and I want to use dynamic column names, by the way this is not about adding columns to an existing data.table.

Here is an example

outer.name <- "outer.column"
outer.members <- c("I", "II")
outer.members.cnt <- length(outer.members)
dt.outerinner <- data.table(outer = outer.members)
setnames(dt.outerinner, outer.name)

Now I want to know, if it's possible to pass the variable "outer.name" directly to data.table(... = outer.members) and omit setnames(...)?

Any hint is appreciated

Tom

11
  • 1
    Can you explain why you are not happy with what you have? It's efficient and very readable code. Commented Sep 9, 2014 at 8:28
  • 3
    I doubt if it possible, although an interesting question. You could do the whole thing in one line if it helps, something like setnames(dt.outerinner <- data.table(outer.name = outer.members), outer.name) Commented Sep 9, 2014 at 9:01
  • 1
    I love chain!! library(magrittr); data.table(outer.members) %>% setnames(outer.name) -> dt.outerinner Commented Sep 9, 2014 at 9:25
  • @Roland I'm happy with what I have. I'm just wondering :-) Commented Sep 9, 2014 at 9:42
  • @DavidArenburg Thanks for your input. My question stems from the fact, that I'm very flexible using .SD and .SDcols when a data.table already exists. So I was just wandering if it's possible to use a variable as a column name (maybe a matter of complete control without the additional setnames function). I'm very happy with the solution, just wanted to make sure that there is no thing missing. Commented Sep 10, 2014 at 8:59

1 Answer 1

2

Could this be what you want?

outer.name <- "outer.column"
outer.members <- c("I", "II")
dtfinal = data.table()
dtfinal[ , (outer.name) := outer.members]

First create a placeholder for you data.table, then update it by reference using the usual := operator. Use parenthesis to pass in a column name programmatically.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.