Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

r - 创建一个空的data.frame(Create an empty data.frame)

I'm trying to initialize a data.frame without any rows.

(我正在尝试初始化没有任何行的data.frame。)

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.

(这将创建一个data.frame,其中包含包含我想要的所有数据类型和列名的单行,而且还会创建一个无用的行,然后将其删除。)

Is there a better way to do this?

(有一个更好的方法吗?)

  ask by Jeff Allen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :

(注意:)

Initializing a data.frame with an empty column of the wrong type does not prevent further additions of rows having columns of different types.

(使用错误类型的空列初始化data.frame不会阻止进一步添加具有不同类型列的行。)
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使用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...