How to add a named vector as a row to a data frame, reordered according to column name order?

一世执手 提交于 2019-12-01 20:09:50

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

Here is why this works:

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

You could reorder the vector

rbind(df, v2[names(df)])
  id va vb vc
1  1 11 21 31
2  2 12 22 32
3  9 19 NA 34


library(microbenchmark)
microbenchmark(rbind(df, v2[names(df)]),
               rbind(df, as.data.frame(t(v2))), times = 10000)
Unit: microseconds
                            expr     min      lq  median      uq      max neval
        rbind(df, v2[names(df)]) 212.773 219.305 222.572 294.895 15300.96 10000
 rbind(df, as.data.frame(t(v2))) 374.219 382.618 387.750 516.067 39951.31 10000
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!