Rbind没有携带空数据的字符串。框架超过[关闭]

问题描述 投票:0回答:1

如何使用空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
r base
1个回答
1
投票

正如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
© www.soinside.com 2019 - 2024. All rights reserved.