Insert column at beginning of a data frame [duplicate]
Asked Answered
L

1

6

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.

Laylalayman answered 4/3, 2014 at 17:35 Comment(4)
cbind(rownames(df), df)?Greatgranduncle
Thank you. I now realize that I asked something really basic but somehow I did not find the answer.Laylalayman
on a side note, are you exporting for using in Weka? There is very little that can be done in Weka that cannot already be done in R without the need for the intermittent stepAcima
@RicardoSaporta Yes it is for using in WEKA. As you might see from my question I am not so familiar with R but have been using WEKA for quite a while. So nevertheless I will probably stay with it. But I will have a look on the machine learning functions in R.Laylalayman
S
7

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
Soundproof answered 4/3, 2014 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.