How to set rownames of a data.frame?

Jasper Hillebrand picture Jasper Hillebrand · May 30, 2013 · Viewed 20k times · Source

I came across an issue when creating a data.frame. When I can create a data.frame, and set the appropriate row and column names.

Results looks like this:

row.names   Africa  ALPS    Benelux

CS MRI Systems  92  151 130

CS Computed To  94  110 91

CS Interv X-Ray 548 535 614

Edit: see that after submitting, my formatting gets lost. Means to show that top left part of the data frame says row.names (RStudio).

This is as intended. I want to write this to excel (write.xlsx), and also that works. However, in the excel, cell A1 is now empty. Instead, I would like to put the name of the month in that cell.

So the question becomes:

  1. Can I change the data.frame such that row.names in the above example is replaced by April?
  2. If not possible, how can I after writing this to an excel sheet, change only cell A1 to April?

I have tried searching on both methods, but cannot find the solution.

Reason why I want this btw, is that if I read from that sheet, and store in a data.frame again, it excludes the row.names from the excel file if the cell A1 is empty.

Answer

csgillespie picture csgillespie · May 30, 2013

Your question doesn't contain enough detail. But basically:

  1. To set rownames in the data frame dd, use

    rownames(dd) = 1:nrow(dd)
    
  2. To write to a csv file, but exclude the row names, use

    write.csv(dd, file="output.csv", row.names=FALSE)
    
  3. To write to a xlsx file, but exclude the row names, use

    write.xlsx(dd, file="output.xlsx", row.names=FALSE)