0

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?

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.