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

后端 未结 2 1452
傲寒
傲寒 2021-01-19 05:53

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?

I need to build a data frame

2条回答
  •  旧时难觅i
    2021-01-19 06:26

    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
    

提交回复
热议问题