How to add a named vector as a string to a data frame

This may have a terribly simple "R" ish solution, but it evades me.

I am working on a problem when I need to create a data frame one row at a time. The named vector is obtained by some processing, and it provides values ​​for the string to be inserted. The problem is that the named vector does not have the components in the same order as the columns of the data frame. This leads to an incorrect rbind result. Here is a very simplified code example

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, as good as it gave the right result. Now the following vector processing results in:

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

This leads to an 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

, . , , ?

, !!!!!

+4
2

v2 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:

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

, , :

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

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
+3

Source: https://habr.com/ru/post/1532990/


All Articles