2
R> data.frame()
data frame with 0 columns and 0 rows

I can make the above data.frame with 0 row and 0 column. How to make a data.frame with 1 row and 0 column?

EDIT: It is absolutely useful, as shown in the following use case.

R> data.frame(data.frame(), y=1)
Error in data.frame(data.frame(), y = 1) :
  arguments imply differing number of rows: 0, 1
R> data.frame(data.frame(x=1)[,0,drop=F], y=1)
  y
1 1
2
  • 5
    You can't have a row without a column I'm afraid. data.frames in R are a list of column vectors. "rows" are just slides across those column vectors. Why are you trying to create such an object? Commented Aug 16, 2021 at 6:17
  • I have upvoted this question because it's about an object that shouldn't be deliberately created, like @MrFlick says. Commented Aug 16, 2021 at 7:13

2 Answers 2

5

This can be done by making a one by one data.frame and selecting the first zero columns:

data.frame(x=1)[,0,drop=FALSE]
#data frame with 0 columns and 1 row

Check that this does have the right dimensions:

dim(data.frame(x=1)[,0,drop=FALSE])
#[1] 1 0 
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting. But note the result does no longer function as a usual dataframe. E.g. rbind(data.frame(x=1)[,0,drop=FALSE], data.frame(x=1)[,0,drop=FALSE]) gives a dataframe with 0 rows instead of two rows as you would expect. I think this is because your structure has one rowonly because of the row.names attribute and not because of content.
I think that it is just a bug in R.
0

This is an alternative solution.

nrow=1 # this can be tuned to return n rows 0 column data.frame.
structure(data.frame(), row.names = seq(nrow))

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.