0

I'm trying to add a column to a dataframe, I usually use the cbind command for adding columns to the end of a dataframe. This time I want to insert a column and make it the first column in the dataframe. I have found similar questions online but the suggested methods were really complicated, like establishing the dataframe from the beginning, is there a simple way to achieve this in one go?

I have a a matrix of 457 column and 9628 row.

Thanks,

Error404
  • 6,959
  • 16
  • 45
  • 58

2 Answers2

3

If you want the column to be the first, just switch the order in cbind:

cbind(c=1:2,data.frame(a=c("a","b"),b=3:4))

Or just order the columns afterwards.

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Hi @Roland, I want to try the command on my data. Can you please explain to me what the a,b and c represent? Many thanks – Error404 Jul 01 '13 at 11:45
  • @Error404 I guess they are just dummy values used to show an example – Michele Jul 01 '13 at 12:01
  • @Michele, I understand they are dummy values. I am asking what should I replace "a" with? is it the column I want to add? or it is it the dataframe? or maybe it is part of the command? I don't know the structure of the formula. Same goes for B and C. – Error404 Jul 01 '13 at 12:06
  • 3
    If you don't understand this you should read an introduction to R. This is extremely basic stuff. – Roland Jul 01 '13 at 12:20
  • I almost finished writing 3 programs in R, Just not familiar with this particular case. I will try to read the cbind help file. Thank you. – Error404 Jul 01 '13 at 12:21
  • 1
    @Error404 that's impressive.. in particular because you've done that without knowing the concept of `named vector` and/or `named list`.. – Michele Jul 01 '13 at 12:40
2

Yeah, you should just switch the ordering of the variables in the arguments to cbind()..

A <- matrix(c(1,2,3,4,5,6),ncol=3)
B <- c(4,5)
C <- cbind(B,A)
endamaco
  • 153
  • 1
  • 11