Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate a column in data frame and rename it to another column name

Tags:

dataframe

r

I have a data frame like sample below. I would like to duplicat a column in the data frame and rename to another column name.

Name    Age    Rate
Aira     23     90
Ben      32     98
Cat      27     95

Desire output is :

Name    Age     Rate     Rate2
Aira    23      90       90
Ben     32      98       98
Cat     27      95       95

How can I do it? Thank you.

like image 642
Ianthe Avatar asked Feb 26 '14 02:02

Ianthe


People also ask

How do I rename a specific column in a data frame?

If you want to rename a single column, just pass the single key-value pair in the columns dict parameter. The result will be the same if there is a non-matching mapping in the columns dictionary.

Can a DataFrame have duplicate column names?

Pandas, however, can be tricked into allowing duplicate column names. Duplicate column names are a problem if you plan to transfer your data set to another statistical language. They're also a problem because it will cause unanticipated and sometimes difficult to debug problems in Python.

Can we rename the column values of data frame?

Renaming Columns of an Existing Dataframe To rename the columns of this DataFrame , we can use the rename() method which takes: A dictionary as the columns argument containing the mapping of original column names to the new column names as a key-value pairs.


2 Answers

Answered with help of user @thelatemail.

df = read.table(sep="",
                header=T, 
                text="Name    Age    Rate
                      Aira     23     90
                      Ben      32     98
                      Cat      27     95")

df$Rate2 = df$Rate #create column 'Rate2' and make it equal to 'Rate' (duplicate).

Another option to duplicate, triplicate or 'n plicate':

#use ?replicate function, which replicates elements over vectors and lists. 
n = 3 #replicate 3 new columns
df3 = cbind(df, replicate(n,df$Rate)) #replicate from column "Rate" in the df object
df3 #plot df3 output

   Name Age Rate 1  2  3
1  Aira 23  90   90 90 90
2  Ben  32  98   98 98 98
3  Cat  27  95   95 95 95
like image 149
Andre Silva Avatar answered Oct 25 '22 11:10

Andre Silva


Replication (making a copy) of a column via dplyr is achieved using mutate:

df <- data.frame(
  Name = c('Aira', 'Ben', 'Cat'),
  Age = c(23, 32, 27),
  Rate = c(90, 98, 95)
)

df <- df %>% 
  mutate(Rate2 = Rate)

#   Name Age Rate Rate2
# 1 Aira  23   90    90
# 2  Ben  32   98    98
# 3  Cat  27   95    95
like image 32
Werner Avatar answered Oct 25 '22 11:10

Werner