2017-04-15 85 views
2

我有下面的數據框。無法更改數據幀列名

> head(weather) 
V6 V7 V8   V9  V10  V11 
1            
2            
3            
4 Day Hour Value  Unit Duration QC Name 
5 1 0 231 \xb5g/m\xb3  1 Hr Valid 
6 1 1 239 \xb5g/m\xb3  1 Hr Valid 

杉杉三行是空的,列名是V6V11。我想用第四行作爲列名。我嘗試了下面的方法,但它不起作用。

colnames(weather) <- weather[4,] 

上面的命令運行後,我的列名變爲:

> colnames(weather) 
[1] "33" "26" "427" "3" "3" "3" 

我不知道這些值的來源。我如何更新數據框中的列名稱?

回答

1

錯誤是由於列的類。它可能是factor,當它被脅迫時存儲模式。這可以在其根部用skip參數讀數被修正

weather <- read.csv("yourfile.csv", skip=4, header=TRUE, stringsAsFactors=FALSE) 

如果我們使用的是OP的方法,那麼unlist行並轉換爲character

colnames(weather) <- as.character(unlist(weather[4,]))