Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert column at beginning of a data frame [duplicate]

Tags:

dataframe

r

arff

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.

like image 571
aldorado Avatar asked Mar 04 '14 17:03

aldorado


1 Answers

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
like image 116
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 19 '22 00:09

A5C1D2H2I1M1N2O1R2T1