Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...