[R] Create a data.table by looping over variable names

András Tajti atajti at gmail.com
Wed Dec 16 13:12:14 CET 2015


Dear Matteo,
I found a one-liner solution to this problem:
n <- 100
data.table(i0 = 100)[, (paste0("i", 1:n)) := 100]

the data.table(i0=100) creates a one column-one row data.table,

Between the [] brakets i create a column name vector with paste, and
surround it with () to make it recognised as names (for details, look at
the Dateails of ?`:=`), and it will append columns to the i0 data.table.

This cannot be done with a 0-column data.table.

Good luck:
András Tajti




On 16 December 2015 at 12:53, Matteo Richiardi <matteo.richiardi at gmail.com>
wrote:

> I apologise for this very basic question, but I found no answers on the
> web.
> I want to create a data.table with n columns, named i1 ... i'n', with only
> one row with value = 100 for every variable.
>
> I can do it "by hand":
>
> M.dt <- data.table(i1=100,i2=100,i3=100)
>
> but I would like to make it in a loop, as 'n' is large in my case.
>
>
> Thanks.
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list