Kumpelka Kumpelka - 11 days ago 7
R Question

R - Construct a data frame with multiple columns without assign

My goal is to create a

data frame
with a number
i
of columns named
ColumnName_1
->
ColumnName_i


The result would be for
i = 3
:

structure(list(ColumnName_1 = c(0, 0, 0), ColumnName_2 = c(0,
0, 0), ColumnName_3 = c(0, 0, 0)), .Names = c("ColumnName_1",
"ColumnName_2", "ColumnName_3"), row.names = c(NA, -3L), class = "data.frame")


I understand from other questions on others topics that it's not recommended to use
assign
but it's the only solution that I see at the moment.

Answer

We can use the following, supposing you want m rows and n columns:

data.frame(matrix(0, nrow = m, ncol = n,
           dimnames = list(NULL, paste0("ColumnName_", 1:n))) )

All other answers uses a loop to create columns, while this solution is fully vectorized.