How to add a line at the top of the data frame 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 add another line on top of the current one:

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

Why this does not work:

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

What is the right way to do this?

+6
source share
2 answers

Put the vector you want on top first:

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

But, using rbind here, it is assumed that all your columns are numeric, and you take the column orders in the same way as the vector. In general, you should bind data.frames together, something like this, where you can mix column types if necessary:

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

There are many other options for more general merging of such data.

+12
source

Why this does not work: new_dat <- rbind (dat, c (0,10000))

In the wrong order, just look at the output:

 R> rbind(dat, c(0, 1000)) V1 V2 1 1 6868 2 2 954 3 3 88 4 0 1000 

Instead, replace the order of the arguments:

 rbind(c(0,10000), dat) 

to get what you want. Alternatively, you could

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

Source: https://habr.com/ru/post/915182/


All Articles