如何将命名向量作为一行添加到数据框中,并根据列名顺序重新排序? [英] How to add a named vector as a row to a data frame, reordered according to column name order?

查看:22
本文介绍了如何将命名向量作为一行添加到数据框中,并根据列名顺序重新排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将命名向量添加到数据框中,并根据数据框的列名对向量的组件进行重新排序?

How to add a named vector to a data frame, with the components of the vector reordered according to the column names of the data frame?

我需要一次构建一个数据框.命名向量是通过一些处理获得的,它为要插入的行提供值.问题是命名向量没有与数据框列顺序相同的组件.这使得 rbind 产生错误的结果.这是非常简化的示例代码:

I need to build a data frame one row at a time. A named vector is obtained by some processing and it provides the values for the row to be inserted. Problem is the named vector doesn't have components in the same order as data frame columns. This makes rbind produce wrong result. Here is the very simplified sample code:

df = data.frame(id=1:2, va=11:12, vb=21:22, vc=31:32)
v1 = c(id=4, va=14, vb=25, vc=NA)
df = rbind(df, v1)

到目前为止,这样就产生了正确的结果.现在下一个向量处理导致:

So far, so good as this produces correct result. Now the next vector processing leads to:

v2 = c(va=19, id=9, vc=34, vb=NA)
df = rbind(df, v2)

这会产生错误的结果.正确的结果应该是

This produces incorrect result. The correct result should be

id va vb vc
1  1 11 21 31
2  2 12 22 32
3  4 14 25 NA
4  9 19 NA 34

推荐答案

rbind 之前用 v2 制作一个数据框:

Make a data frame out of v2 prior to the rbind:

rbind(df, as.data.frame(t(v2)))
##   id va vb vc
## 1  1 11 21 31
## 2  2 12 22 32
## 3  4 14 25 NA
## 4  9 19 NA 34

这就是为什么这样做:

v2 有名称,但它的作用类似于 as.data.frame 的列向量:

v2 has names, but it acts like a column vector to as.data.frame:

as.data.frame(v2)
##    v2
## va 19
## id  9
## vc 34
## vb NA

因此,您必须将数据转置为正确的形式:

Thus, you must transpose the data to put it into the correct form:

as.data.frame(t(v2))
##   va id vc vb
## 1 19  9 34 NA

这篇关于如何将命名向量作为一行添加到数据框中,并根据列名顺序重新排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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