Maxxx
Maxxx

Reputation: 3768

Duplicating column in a dataframe in R

I have an example of dataframe below:

Name       Class      ID
Terry      C-02       100
Jane       C-03       101
Tom        C-04       102

I want to duplicate the ID column and place it at the start of the dataframe like so:

ID       Name      Class      ID
100      Terry     C-02       100
101      Jane      C-03       101
102      Tom       C-04       102

I tried:

id_col <- as.data.frame(df$ID)
new_df <- cbind(id_col, df)

But I'm getting a "Large matrix" instead of a regular dataframe.

Upvotes: 0

Views: 58

Answers (4)

G. Grothendieck
G. Grothendieck

Reputation: 269644

Assuming you want exactly the result shown then the main problem is to have R not rename the second instance of the column name ID to ID.1. If we convert to list and back then we can use check.names = FALSE on as.data.frame like this:

as.data.frame(as.list(DF)[c(3, 1:3)], check.names = FALSE)

giving:

   ID  Name Class  ID
1 100 Terry  C-02 100
2 101  Jane  C-03 101
3 102   Tom  C-04 102

Note

Lines <- "Name       Class      ID
Terry      C-02       100
Jane       C-03       101
Tom        C-04       102"
DF <- read.table(text = Lines, header = TRUE, strip.white = TRUE)

Upvotes: 1

NelsonGon
NelsonGon

Reputation: 13319

Here are a few approaches:

Use the ID as an attribute to avoid duplicate names:

structure(df, row.names= df$ID)
     Name Class  ID
100 Terry  C-02 100
101  Jane  C-03 101
102   Tom  C-04 102

Use dplyr's select to introduce a new duplicate ID:

    df %>% 
 mutate(new_ID = ID) %>% 
 select(new_ID, everything())
  new_ID  Name Class  ID
1    100 Terry  C-02 100
2    101  Jane  C-03 101
3    102   Tom  C-04 102

base:

 data.frame(ID=df$ID,df,check.names = FALSE)
   ID  Name Class  ID
1 100 Terry  C-02 100
2 101  Jane  C-03 101
3 102   Tom  C-04 102

Upvotes: 3

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

One more (actually close to what you tried initially):

df1 <- cbind(df[, c(3, 1:2)], ID=df$ID)
df1
   ID  Name Class  ID
1 100 Terry  C-02 100
2 101  Jane  C-03 101
3 102   Tom  C-04 102

Upvotes: 2

jay.sf
jay.sf

Reputation: 72828

Here my 50 cent.

df1[c(3, 1:3)]
#    ID  Name Class ID.1
# 1 100 Terry  C-02  100
# 2 101  Jane  C-03  101
# 3 102   Tom  C-04  102

cbind(df1[3], df1)
#    ID  Name Class  ID
# 1 100 Terry  C-02 100
# 2 101  Jane  C-03 101
# 3 102   Tom  C-04 102

Upvotes: 4

Related Questions