Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add row on-top of data frame R

Tags:

dataframe

r

I have the following data frame:

> dat

  V1   V2
1  1 6868
2  2  954
3  3   88

What I want to do is to add another row on top of the current one resulting:

   V1   V2
1  0 10000
2  1 6868
3  2  954
4  3   88

Why this doesn't work:

new_dat <- rbind(dat,c(0,10000))

What's the correct way to do it?

like image 977
pdubois Avatar asked May 08 '12 10:05

pdubois


1 Answers

Put the vector you want on top first:

new_dat <- rbind(c(0,10000), dat)

But, using rbind here assumes that all your columns are numeric, and you are assuming column orders the same as the vector. In general you should bind data.frames together, something like this, where you can mix column types if needed:

rbind(data.frame(V1 = 0, V2 = 10000), dat)

There are many other options for a more general merge of data like this.

like image 178
mdsumner Avatar answered Sep 21 '22 01:09

mdsumner