Insert column at beginning of a data frame

aldorado picture aldorado · Mar 4, 2014 · Viewed 8.7k times · Source

How can I add a column to an R data.frame as a new first column so that all other columns are shifted by one column?

Like:

a|b|c --> new|a|b|c

I need to do this because I want the row.names to become a discrete column. This is needed because the write.arff function takes a data.frame as input but does not preserve the names when writing files.

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Jul 10, 2014

This has been answered in the comments, but to make it clearer that there is an answer, here's a small example:

First, some sample data:

(df <- data.frame(A = 1:2, B = 3:4, row.names = c("row1", "row2")))
#      A B
# row1 1 3
# row2 2 4

The suggestion from the comments. Note that the original row.names is still part of the data.

cbind(rn = rownames(df), df)
#        rn A B
# row1 row1 1 3
# row2 row2 2 4

You can get rid of that by setting row.names = NULL in the cbind step. Since you are cbinding data.frames, you could also pass other arguments to data.frame if necessary (such as stringsAsFactors = FALSE if you didn't want the "rn" column to be a factor).

cbind(rn = rownames(df), df, row.names = NULL)
#     rn A B
# 1 row1 1 3
# 2 row2 2 4