user15502206
user15502206

Reputation: 131

How to make a data.frame with 1 row 0 column?

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

Upvotes: 2

Views: 902

Answers (2)

user15502206
user15502206

Reputation: 131

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))

Upvotes: 0

Miff
Miff

Reputation: 7941

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 

Upvotes: 5

Related Questions