我试图初始化一个data。frame,没有任何行。基本上,我希望为每个列指定数据类型并命名它们,但结果不创建任何行。

到目前为止,我能做的最好的事情是:

df <- data.frame(Date=as.Date("01/01/2000", format="%m/%d/%Y"), 
                 File="", User="", stringsAsFactors=FALSE)
df <- df[-1,]

它创建了一个data.frame,包含我想要的所有数据类型和列名的单行,但也创建了一个无用的行,然后需要删除。

还有更好的办法吗?


当前回答

只需用空向量初始化它:

df <- data.frame(Date=as.Date(character()),
                 File=character(), 
                 User=character(), 
                 stringsAsFactors=FALSE) 

下面是另一个不同列类型的例子:

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没有行,它也能工作。

其他回答

通过使用数据。表中我们可以为每一列指定数据类型。

library(data.table)    
data=data.table(a=numeric(), b=numeric(), c=numeric())

你可以用read。表中输入的文本为空字符串,如下所示:

colClasses = c("Date", "character", "character")
col.names = c("Date", "File", "User")

df <- read.table(text = "",
                 colClasses = colClasses,
                 col.names = col.names)

或者将col.names指定为字符串:

df <- read.csv(text="Date,File,User", colClasses = colClasses)

感谢Richard Scriven的改进

只是声明

table = data.frame()

当您尝试rbind第一行时,它将创建列

我使用以下代码创建了空数据帧

df = data.frame(id = numeric(0), jobs = numeric(0));

并尝试绑定一些行来填充,如下所示。

newrow = c(3, 4)
df <- rbind(df, newrow)

但是它开始给出如下错误的列名

  X3 X4
1  3  4

解决方案是将newrow转换为df类型,如下所示

newrow = data.frame(id=3, jobs=4)
df <- rbind(df, newrow)

现在给出正确的数据帧时显示列名如下

  id nobs
1  3   4 

如果你不介意不显式地指定数据类型,你可以这样做:

headers<-c("Date","File","User")
df <- as.data.frame(matrix(,ncol=3,nrow=0))
names(df)<-headers

#then bind incoming data frame with col types to set data types
df<-rbind(df, new_df)