In R, If I make a data.frame with one column, I can added others
在R中,如果我用一个列做一个数据
> data <- data.frame(n=c(1:4))
> data
n
1 1
2 2
3 3
4 4
> data$n2 <- 2
> data
n n2
1 1 2
2 2 2
3 3 2
4 4 2
but, If I make a empty data.frame, I can't add new columns
但是,如果我创建一个空的data.frame,我不能添加新的列
> data <- data.frame()
> data
data frame with 0 columns and 0 rows
> data$n2 <- 2
Error in `$<-.data.frame`(`*tmp*`, "n2", value = 2) :
replacement has 1 row, data has 0
why ? how I can add new columns to empty data.frame ?
为什么?如何向空data.frame添加新列?
1 个解决方案
#1
4
You can add a column to an empty data.frame, but to match the existing data.frame's dimensions, the assigned vector needs to have length zero:
您可以向空数据。frame,但是要匹配现有数据。frame的维度,所分配的向量必须具有长度为零的值:
data <- data.frame()
data$n2 <- numeric()
data
# [1] n2
# <0 rows> (or 0-length row.names)
(In your first example, although the value on the RHS of the assignment didn't have the same length as the existing columns, it was "recycled" to form a column of the necessary length. When the existing data.frame has no rows, though, recycling can't be used to make the column lengths match.)
(在您的第一个示例中,尽管赋值的RHS上的值与现有列的长度不相同,但它被“回收”以形成必要长度的列。但是,当现有的data.frame没有行时,回收不能用于使列长度匹配。
#1
4
You can add a column to an empty data.frame, but to match the existing data.frame's dimensions, the assigned vector needs to have length zero:
您可以向空数据。frame,但是要匹配现有数据。frame的维度,所分配的向量必须具有长度为零的值:
data <- data.frame()
data$n2 <- numeric()
data
# [1] n2
# <0 rows> (or 0-length row.names)
(In your first example, although the value on the RHS of the assignment didn't have the same length as the existing columns, it was "recycled" to form a column of the necessary length. When the existing data.frame has no rows, though, recycling can't be used to make the column lengths match.)
(在您的第一个示例中,尽管赋值的RHS上的值与现有列的长度不相同,但它被“回收”以形成必要长度的列。但是,当现有的data.frame没有行时,回收不能用于使列长度匹配。