简体   繁体   English

将数据添加到空r data.frame

[英]Add data to empty r data.frame

In R, If I make a data.frame with one column, I can added others 在R中,如果我创建一个包含一列的data.frame,我可以添加其他列

> 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?

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: 可以向空data.frame添加列,但要匹配现有data.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没有行时但是,回收不能用于使列长度匹配。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM