Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...