如何在R中添加带有额外列的新行?
我试图将 for 循环的结果作为新行添加到数据帧中,但是当新结果的列数多于原始数据帧时,它会出现错误,如何将具有额外列的新结果添加到数据帧中将额外的列名称添加到原始数据框中?
例如 原始数据帧:
-______A BC
- x1 1 1 1
- x2 2 2 2
- x3 3 3 3
我想得到
-______A BCD
- x1 1 1 1 NA
- x2 2 2 2 NA
- x3 3 3 3 NA
- X4 4 4 4 4
我尝试了 rbind (错误在 rbind(deparse.level, ...) 中: 参数的列数不匹配) 和 rbind_fill (错误:rbind.fill 的所有输入都必须是 data.frames) 和bind_rows(参数2必须有名称)
I was trying to add results of a for loop into a dataframe as new rows, but it gets an error when there is a new result with more columns than the original dataframe, how could I add the new result with extra columns to the dataframe with adding the extra column names to the original dataframe?
e.g.
original dataframe:
-______A B C
- x1 1 1 1
- x2 2 2 2
- x3 3 3 3
I want to get
-______A B C D
- x1 1 1 1 NA
- x2 2 2 2 NA
- x3 3 3 3 NA
- X4 4 4 4 4
I tried rbind (Error in rbind(deparse.level, ...) :
numbers of columns of arguments do not match)
and rbind_fill (Error: All inputs to rbind.fill must be data.frames)
and bind_rows (Argument 2 must have names)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
base R
中,可以通过使用NA
创建一个新列“D”,然后用4分配新行来完成。-output
或者在单行中
关于错误在
bind_rows
中,当for
循环输出不是命名向量时会发生这种情况如果它是命名向量,那么它应该工作
数据
In
base R
, this can be done by creating a new column 'D' withNA
and then assign new row with 4.-output
Or in a single line
Regarding the error in
bind_rows
, it happens when thefor
loop output is not a named vectorIf it is a named vector, then it should work
data
如果您
列出
for
循环的元素,您可能会遇到类似的情况。可以使用
do.call(rbind, .)
方法来rbind
编辑,您的问题是,如何rbind
多个不同的元素在长度
中。有一个
`length<-`
函数,您可以使用它来调整向量的长度。要了解长度,可以使用另一个函数lengths
,它可以为您提供每个列表元素的长度,您对其中的max
imum 感兴趣。我包括了元素长度为
NULL
的特殊情况(我们的l
的第 5th 元素);由于 NULL 的长度无法更改,因此将这些元素替换为 NA。因此,您总共可以这样做:
或者,因为您可能想要一个具有漂亮的行和列名称的数据框:
注意:使用 R >= 4.1。
数据:
You probably have something like this, if you
list
the elements of yourfor
loop.Multiple elements can be
rbind
ed using ado.call(rbind, .)
approach, your problem is, how torbind
multiple elements that differ inlength
.There's a
`length<-`
function with which you may adjust the length of a vector. To know to which length, there's another function,lengths
, that gives you the lengths of each list element, where you are interested in themax
imum.I include the special case when an element has length
NULL
(our 5th element ofl
); since length of NULL cannot be changed,replace
those elements withNA
.So altogether you may do:
Or, since you probably want a data frame with pretty row and column names:
Note: R >= 4.1 used.
Data: