skan
skan

Reputation: 7730

R data.table. generate variable names

I want to generate a datatable with many columns, with names generated automatically, such as this:

data.table(paste0("A",10:24)=1:15)

or

data.table(paste0("A",10:24)=rep(runif(100), 15)

but I get this error:

Error: unexpected '=' in "data.table(paste0("A",10:24)="

How can I do it?

Upvotes: 1

Views: 163

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99341

There are multiple ways to do this. Here are three. Create the table first, then set the names. Or, create a named list and coerce it to data table.

setnames(as.data.table(as.list(1:15)), paste0("A", 10:24))[]
#    A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24
# 1:   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

do.call(data.table, setNames(as.list(1:15), paste0("A", 10:24)))
#    A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24
# 1:   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

as.data.table(setNames(as.list(1:15), paste0("A", 10:24)))
#    A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24
# 1:   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

## just for fun ...
fread(paste(c(paste0("A", 10:24), "\n", 1:15), collapse = " "))
#    A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24
# 1:   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

Upvotes: 2

Related Questions