R: Insert a vector as a row in data.frame

前端 未结 3 1063
孤独总比滥情好
孤独总比滥情好 2020-12-14 01:04

Can I insert a vector as a row in a data.frame? If so how?

3条回答
  •  忘掉有多难
    2020-12-14 01:23

    I wouldn't claim this to be the most elegant and pretty solution out there, but it gets the job done. Notice that each dataframe row carries its own row name, which becomes a problem when inserting new lines. That being said, you can mend this with row.names (see below).

    my.df <- data.frame(a = runif(10), b = runif(10), c = runif(10))
    my.vec <- c(1, 1, 1)
    new.df <- rbind(my.df[1:5, ], my.vec, my.df[6:nrow(my.df), ])
    new.df
                a         b          c
    1  0.45433791 0.3798105 0.84514864
    2  0.07074529 0.4985765 0.53912585
    3  0.09645574 0.5441647 0.96636213
    4  0.60788436 0.6070706 0.53791603
    5  0.01593911 0.1697248 0.62697924
    6  1.00000000 1.0000000 1.00000000
    61 0.98455694 0.2206702 0.85500531
    7  0.85356834 0.5279596 0.27462326
    8  0.48028935 0.6689572 0.05428349
    9  0.95675901 0.6875491 0.77642924
    10 0.24691330 0.7980741 0.24013096
    
    row.names(new.df) <- 1:nrow(new.df)  # make row names pretty again
    

提交回复
热议问题