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

后端 未结 2 1450
傲寒
傲寒 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
    慢半拍i (楼主)
    2021-01-19 06:15

    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
    

提交回复
热议问题