如何使用空data.frame进行rbind?它只在至少有一行时才携带列名,但在空行时则不携带。通常在for循环之前创建空data.frame,因此这种行为很烦人。
例:
test= data.frame(a=1, b=2, c=3)
rbind(test, c(3,4,5))
a b c
1 1 2 3
2 3 4 5
test= data.frame(matrix(ncol= 3, nrow= 0))
names(test) = c("a", "b", "c")
rbind(test, c(3,4,5))
X3 X4 X5
1 3 4 5
正如Dan Y指出的那样,预期的行为不是一个错误。
data.table可以做到这一点
library(data.table)
# Create empty data.frame
test <- data.frame(matrix(ncol= 3, nrow= 0))
# Give it names
names(test) <- c("a", "b", "c")
# Coerce to data.table
setDT(test)
# rbind vector (set as a list)
x <- rbind(test, as.list(c(3,4,5)), use.names = F, fill = F)
# Coerce back to a data.frame if you wish
setDF(x)
x
> a b c
1 3 4 5