如何将具有不同行数的列附加到 R 中的数据框中? [英] how to append a column with different row count into a data frame in R?

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

问题描述

假设有一个固定行数的数据框,例如

Suppose there is a data frame with a fixed number of row, for example

a <- as.data.frame(c(1:7))

还有另一个行数更少(或更多)的向量:

And there is another vector with fewer (or bigger) number of row:

b <- c(1:4)

那么就不可能将 b 作为新列添加到 a 中:

Then it is not possible to add b as new column into a:

a <- cbind(a, b)

输出如下:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 7, 4

预期结果如下:

1      1      1
2      2      2
3      3      3
4      4      4
5      5     NA
6      6     NA
7      7     NA

推荐答案

我们可以使用 rowr

rowr::cbind.fill(a, b, fill = NA)

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

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