2

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.

Kumpelka
  • 869
  • 3
  • 11
  • 33

3 Answers3

6

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.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
1

Here is a method that uses replicate and data.frame to construct an empty data.frame of whatever size you'd like (with numeric variables) and then uses setNames to provide variable names.

setNames(data.frame(replicate(3, numeric(3), simplify=FALSE)),
         paste0("colName", seq_len(3)))

  colName1 colName2 colName3
1        0        0        0
2        0        0        0
3        0        0        0

The first argument to replicate provides the number of columns and the second argument numeric(3) provides the number of rows.

lmo
  • 37,904
  • 9
  • 56
  • 69
1

A version with lapply.

i <- 3
setNames(as.data.frame(lapply(1:i, function(k) c(0, 0, 0))),
         paste("ColumnName_", 1:i, sep = ""))
Kota Mori
  • 6,510
  • 1
  • 21
  • 25