Creating empty dataframe with column names as in a vector

to add to PJ's solution:
you can also declare the colnames while constructing the matrix.

x <- c('a','b','c')

df <- as.data.frame(
  matrix(ncol = length(x), nrow=0,
             dimnames = list(NULL,x))
)

the dimnames argument must be a list of 2 vectors, first the rownames, then the colnames

1 Like