Kumpelka Kumpelka - 1 year ago 82
R Question

Construct a data frame with multiple columns without assign

My goal is to create a

data frame
with a number
of columns named

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
but it's the only solution that I see at the moment.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download