我有一個數據框,如下面的示例。我想複製數據框中的一列並重命名爲另一個列名。複製數據框中的列並將其重命名爲另一個列名
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
我該怎麼辦呢?謝謝。
我有一個數據框,如下面的示例。我想複製數據框中的一列並重命名爲另一個列名。複製數據框中的列並將其重命名爲另一個列名
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
我該怎麼辦呢?謝謝。
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
'rep(df $ Rate)'和'df $ Rate'一樣,因爲有一個默認的'times = 1'沒有參數。在這種情況下'rep(df $ Rate,2)'及以上將不起作用,並且會產生瘋狂的結果。 'cbind(df,replicate(2,df $ Rate))'將會起作用。 – thelatemail
感謝thelatemail&Andre爲您解答。 – Ianthe
@lanthe,不客氣。根據電郵的建議,答案得到了改善。 –
'df $ Rate2 < - df $ Rate'? – thelatemail
@thelatemail,非常感謝。你一直很有幫助。我對R非常陌生。:) – Ianthe