Home > Software engineering >  add col name to row name for csv file
add col name to row name for csv file

Time:12-02

Is there a way to add a col name for the row name field if I use the rownames for an output file?

I know it cannot be done in this function (unless I am completely wrong):

colnames(df)<-c("fullname","addr1","addr2","City","State","ZIP","Keycode","csz")

Is there an argument for the write.csv() function to accomplish it?

CodePudding user response:

You can easily use cbind for this:

df <- cbind(myname = row.names(mtcars), mtcars)
write.csv(df, row.names = FALSE)

You practically add the row names as a new column (with your selected column name) and you write your csv without row.names in this case.

      myname  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4                     Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag             Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710                   Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive           Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout     Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant                         Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360                   Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
  • Related