创建一个空的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,]
其中创建一个包含我想要的所有数据类型和列名称的单行的数据框架,但是还会创建一个无用的行,然后需要删除。
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?
推荐答案
只需用空的向量初始化它:
Just initialize it with empty vectors:
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
NB :
使用错误类型的空列初始化 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屋!