Duplicate the column in the data frame and rename it to a different column name

I have a data frame, for example, a sample. I would like to duplicate a column in a data frame and rename it to another column name.

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

Desired conclusion:

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

How can i do this? Thank.

+8
source share
2 answers

Answered using @thelatemail user.

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 for duplication, duplication 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
+10
source

Replication (creating a copy) of a column using is dplyrachieved using mutate:

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

df %>% 
  mutate(Rate2 = Rate)

#   Name Age Rate Rate2
# 1 Aira  23   90    90
# 2  Ben  32   98    98
# 3  Cat  27   95    95
+1
source

All Articles