创建一个空的 data.frame [英] Create an empty data.frame
问题描述
我正在尝试初始化一个没有任何行的 data.frame.基本上,我想为每一列指定数据类型并命名它们,但不会因此创建任何行.
I'm trying to initialize a data.frame without any rows. Basically, I want to specify the data types for each column and name them, but not have any rows created as a result.
到目前为止我能做的最好的是:
The best I've been able to do so far is something like:
df <- data.frame(Date=as.Date("01/01/2000", format="%m/%d/%Y"),
File="", User="", stringsAsFactors=FALSE)
df <- df[-1,]
它创建了一个 data.frame,其中一行包含我想要的所有数据类型和列名,但也创建了一个无用的行,然后需要将其删除.
Which creates a data.frame with a single row containing all of the data types and column names I wanted, but also creates a useless row which then needs to be removed.
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
用空向量初始化即可:
df <- data.frame(Date=as.Date(character()),
File=character(),
User=character(),
stringsAsFactors=FALSE)
<小时>
这是另一个具有不同列类型的示例:
Here's an other example with different column types :
df <- data.frame(Doubles=double(),
Ints=integer(),
Factors=factor(),
Logicals=logical(),
Characters=character(),
stringsAsFactors=FALSE)
str(df)
> str(df)
'data.frame': 0 obs. of 5 variables:
$ Doubles : num
$ Ints : int
$ Factors : Factor w/ 0 levels:
$ Logicals : logi
$ Characters: chr
注意:
使用错误类型的空列初始化 data.frame
不会阻止进一步添加具有不同类型列的行.
这种方法有点更安全,因为您将从一开始就拥有正确的列类型,因此如果您的代码依赖于某些列类型检查,它甚至可以使用 data.frame
零行.
Initializing a data.frame
with an empty column of the wrong type does not prevent further additions of rows having columns of different types.
This method is just a bit safer in the sense that you'll have the correct column types from the beginning, hence if your code relies on some column type checking, it will work even with a data.frame
with zero rows.
这篇关于创建一个空的 data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!