2014-02-26 91 views
2

我有一个数据框,如下面的示例。我想复制数据框中的一列并重命名为另一个列名。复制数据框中的列并将其重命名为另一个列名

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

欲望输出为:

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

我该怎么办呢?谢谢。

+1

'df $ Rate2 < - df $ Rate'? – thelatemail

+0

@thelatemail,非常感谢。你一直很有帮助。我对R非常陌生。:) – Ianthe

回答

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

溶液1,通过@thelatemail提供

df$Rate2 = df$Rate 

另一种解决方案:

#use the function rep, which "replicates elements of vectors and lists". see ?rep 
df2 = cbind(df,Rate2=rep(df$Rate)) 

编辑 - 一式三份(或 “n折扇”)列作为建议在评论,由@thelatemail。

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

'rep(df $ Rate)'和'df $ Rate'一样,因为有一个默认的'times = 1'没有参数。在这种情况下'rep(df $ Rate,2)'及以上将不起作用,并且会产生疯狂的结果。 'cbind(df,replicate(2,df $ Rate))'将会起作用。 – thelatemail

+0

感谢thelatemail&Andre为您解答。 – Ianthe

+0

@lanthe,不客气。根据电邮的建议,答案得到了改善。 –

相关问题