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
  • 809
  • 3
  • 11
  • 29

3 Answers3

5

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
  • 62,170
  • 17
  • 162
  • 226
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
  • 36,904
  • 9
  • 50
  • 61
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
  • 5,663
  • 17
  • 23