2014-01-28 26 views
0

我想用第一行中的標頭替換data.frame的標頭。 數據已使用read.xls()導入。不幸的是沒有選擇再讀入原始文件。R用行中的名稱替換標頭

 bad header here 
1 new header2 here 
2 58 3.222  50 
3 25 10.000 40 
4 5 0.847  152.5 
5 15 1.633  98 

結果應該是這樣的:

new header2 here 
1 58 3.222  50 
2 25 10.000 40 
3 5 0.847  152.5 
4 15 1.633  98 

感謝,

馬特

回答

1

假設你的數據被稱爲my.data。幀只是分配第1行到頭,然後刪除第1行

#assign row 1 names to the header   
    names(my.data.frame) <- as.character(my.data.frame[1,]) 

    #delete the first row 
    my.data.frame <- my.data.frame[2:nrow(my.data.frame),] 
+0

但是OP明確表示他不再有權訪問源文件。 –

+0

名稱和as.character的組合正是我所需要的。謝謝。 @carl該解決方案無需重新讀取數據集即可運行! – mace

1

假設你data.frame被稱爲 「myDF上」,你可以嘗試這樣的事:

df2 <- setNames(mydf[-1, ], mydf[1, ]) 

但是,您的數據都將取決於他們如何在最初閱讀是字符或因素

str(df2) 
# 'data.frame': 4 obs. of 3 variables: 
# $ new : chr "58" "25" "5" "15" 
# $ header2: chr "3.222" "10.000" "0.847" "1.633" 
# $ here : chr "50" "40" "152.5" "98" 

您可以轉換如下:

df2[] <- lapply(df2, function(x) type.convert(as.character(x))) 
str(df2) 
# 'data.frame': 4 obs. of 3 variables: 
# $ new : int 58 25 5 15 
# $ header2: num 3.222 10 0.847 1.633 
# $ here : num 50 40 152 98 
df2 
# new header2 here 
# 2 58 3.222 50.0 
# 3 25 10.000 40.0 
# 4 5 0.847 152.5 
# 5 15 1.633 98.0