将列添加到R中的空数据框 [英] Add Columns to an empty data frame in R

查看:2279
本文介绍了将列添加到R中的空数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经广泛搜索过,但没有在Stack Overflow上找到这个问题的答案。 b

我定义:

  a<  -  NULL 
a < - as.data 。框(a)

如果我想像这样添加一个列到这个数据框: p>

  a $ col1<  -  c(1,2,3)

我收到以下错误:

  $< ;  - 。data.frame`(`* tmp *`,a,value = c(1,2,3)):
替换有3行,数据有0

为什么行尺寸固定不变,但列不是?



我更改数据帧中的行数?



如果我这样做(首先将数据输入列表然后转换为df),它的工作正常:

  a<  -  NULL 
a $ col1< - c(1,2,3)
a < - as.data.frame(a)


解决方

行尺寸不是固定的,而是data.frames被存储为被限制为具有相同的长度的矢量的列表。您不能将 col1 添加到 a ,因为 col1 具有三个值(行)和 A 具有零,从而断开该约束。 R'当你试图通过添加一列是比data.frame更长的时间来延长data.frame的尺寸由默认自动vivify值没有。第二个例子的原因是, col1 是data.frame中唯一的向量,因此data.frame将被三行初始化。



如果要自动使data.frame展开,可以使用以下功能:

  cbind.all<  -  function(...)
{
nm < - list(...)
nm< - lapply ,as.matrix)
n < - max(sapply(nm,nrow))
do.call(cbind,lapply(nm,function(x)rbind(x,matrix(,n -
nrow(x),ncol(x)))))
}

将填补缺失值与 NA 。你会使用它: cbind.all(df,a)


I have searched extensively but not found an answer to this question on Stack Overflow.

Lets say I have a data frame a.

I define:

a <- NULL
a <- as.data.frame(a)

If I wanted to add a column to this data frame as so:

a$col1 <- c(1,2,3)

I get the following error:

Error in `$<-.data.frame`(`*tmp*`, "a", value = c(1, 2, 3)) : 
    replacement has 3 rows, data has 0

Why is the row dimension fixed but the column is not?

How do I change the number of rows in a data frame?

If I do this (inputting the data into a list first and then converting to a df), it works fine:

a <- NULL
a$col1 <- c(1,2,3)
a <- as.data.frame(a)

解决方案

The row dimension is not fixed, but data.frames are stored as list of vectors that are constrained to have the same length. You cannot add col1 to a because col1 has three values (rows) and a has zero, thereby breaking the constraint. R does not by default auto-vivify values when you attempt to extend the dimension of a data.frame by adding a column that is longer than the data.frame. The reason that the second example works is that col1 is the only vector in the data.frame so the data.frame is initialized with three rows.

If you want to automatically have the data.frame expand, you can use the following function:

cbind.all <- function (...) 
{
    nm <- list(...)
    nm <- lapply(nm, as.matrix)
    n <- max(sapply(nm, nrow))
    do.call(cbind, lapply(nm, function(x) rbind(x, matrix(, n - 
        nrow(x), ncol(x)))))
}

This will fill missing values with NA. And you would use it like: cbind.all( df, a )

这篇关于将列添加到R中的空数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆