Reputation: 7790
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?
Upvotes: 15
Views: 52589
Reputation: 60452
Why doesn't this work: new_dat <- rbind(dat,c(0,10000))
It's 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, swap the order of the arguments:
rbind(c(0,10000), dat)
to get what you want. Alternatively, you could have
rbind(data.frame(V1 = 0, V2 = 10000), dat)
Upvotes: 9
Reputation: 29477
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.
Upvotes: 22