Reputation: 2095
I need to create a data.frame with no rows but specified column names and column types that is about to be filled later. As I want to have 1000 columns, defining columns one by one (as seen below) is not an option.
data.frame(a1 = character(), a2 = character(), ..., a1000 = character())
I was thinking that maybe paste
function can be used to create a sequence of names, but the following doesn't work.
data.frame(paste('a', 1:1000, sep = '') = character())
Any ideas how it can be achieved?
Upvotes: 0
Views: 1059
Reputation: 4873
While it's very similar to @Nick Criswell, you can also do this:
df <- data.frame(replicate(1000,sample(0:1,0,rep=TRUE)))
> dim(df)
[1] 0 1000
> class(df)
[1] "data.frame"
Upvotes: 3
Reputation: 1743
There might be a way to do this in one line, but an option is to first make an empty matrix, convert that to a data frame and then change the names.
df <- data.frame(matrix("NA", nrow = 0, ncol = 1000), stringsAsFactors = FALSE)
names(df) <- paste("a", 1:1000, sep = "")
> dim(df)
[1] 0 1000
> class(df)
[1] "data.frame"
Upvotes: 1