Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create data.table with column name from string variable

Tags:

r

data.table

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

like image 598
Tom Martens Avatar asked Nov 11 '22 02:11

Tom Martens


1 Answers

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.

like image 153
Francesco Grossetti Avatar answered Nov 15 '22 06:11

Francesco Grossetti