我通过执行" flattening"的相反操作来创建新的data.frame。输入data.frame(换句话说,来自"宽"到"窄",创建更多行)。
我将循环输入data.frame的列,并附加到输出data.frame。我知道创建完整的输出data.frame更有效率并在循环中填充它,但我的问题是为什么可以创建一个0 x 4 data.frame,但显然不可能命名那些4栏......谢谢。
dff <- data.frame()
dim( dff ) <- c(0,4)
colnames(dff) <- c("first","second","third","fourth")
Error in `colnames<-`(`*tmp*`, value = c("first", "second", "third", "fourth" :
'names' attribute [4] must be the same length as the vector [0]
答案 0 :(得分:1)
以下是四种可能性(我确定还有其他可能性):
> data.frame(first=numeric(), second=numeric(), third=numeric(), fourth=numeric())
[1] first second third fourth
<0 rows> (or 0-length row.names)
> data.frame(first=1,second=1,third=1,fourth=1)[0,]
[1] first second third fourth
<0 rows> (or 0-length row.names)
> as.data.frame(matrix(nrow=0,ncol=4,dimnames=list(c(),c("first","second","third","fourth"))))
[1] first second third fourth
<0 rows> (or 0-length row.names)
> setNames(as.data.frame(matrix(nrow=0,ncol=4)), c("first","second","third","fourth"))
[1] first second third fourth
<0 rows> (or 0-length row.names)
请注意,对于第一个解决方案,您可以指定所需的任何列类(例如,将numeric()
替换为character()
等)。
此外,您无法指定data.frame的dim
属性,因为data.frames没有dim
属性。相反,they are a list
structure with a row.names
attribute。 str
函数有助于理解这些对象是什么。