在数据框中复制一列并将其重命名为另一个列名 [英] Duplicate a column in data frame and rename it to another column name

查看:83
本文介绍了在数据框中复制一列并将其重命名为另一个列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,例如下面的示例。我想在数据框中复制一列,然后重命名为另一个列的名称。

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

期望输出为:

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

我该怎么办?谢谢。

推荐答案

在用户@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).

另一种复制,重复或 n plicate的选项:

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

这篇关于在数据框中复制一列并将其重命名为另一个列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆