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

后端 未结 2 2049
刺人心
刺人心 2020-12-15 08:25

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         


        
相关标签:
2条回答
  • 2020-12-15 09:13

    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
    
    0 讨论(0)
  • 2020-12-15 09:26

    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
    
    0 讨论(0)
提交回复
热议问题