2017-09-26 57 views
0

我有一個更大的數據集,當我導入到R,和不同類型的特殊字符的列名。爲什麼R變成特殊字符列名成點

當我使用此數據集作爲另一個變量的副本或作爲另一個較小數據的子集或執行不同類型的數據轉換(來自同一較大數據集的數據和列名稱)時,列名稱中的所有特殊字符都會更改到.

有沒有辦法在列名保存特殊字符?我不希望R相對於列名更改任何內容。

請提出解決方案。

> library(MASS) 
> data(cats) 
> cats <- cats[1:10,] 
> cats 
    Sex Bwt Hwt 
1 F 2.0 7.0 
2 F 2.0 7.4 
3 F 2.0 9.5 
4 F 2.1 7.2 
5 F 2.1 7.3 
6 F 2.1 7.6 
7 F 2.1 8.1 
8 F 2.1 8.2 
9 F 2.1 8.3 
10 F 2.1 8.5 
> colnames(cats) <- c("A:17272,,1,MPR.rtn_rslt", "B:17272,,1,MPR.rtn_rslt", "C:17272,,1,MPR.rtn_rslt") 
> cats 
    A:17272,,1,MPR.rtn_rslt B:17272,,1,MPR.rtn_rslt C:17272,,1,MPR.rtn_rslt 
1      F      2.0      7.0 
2      F      2.0      7.4 
3      F      2.0      9.5 
4      F      2.1      7.2 
5      F      2.1      7.3 
6      F      2.1      7.6 
7      F      2.1      8.1 
8      F      2.1      8.2 
9      F      2.1      8.3 
10      F      2.1      8.5 

cats數據組具有特殊字符,:列名。下面,我正在執行數據轉換。

> # Define the avector-subselection method 
> as.data.frame.avector <- as.data.frame.vector 
> `[.avector` <- function(x,i,...) { 
+ r <- NextMethod("[") 
+ mostattributes(r) <- attributes(x) 
+ r 
+ } 

> # Preserve attributes as they are lost due to subet 
> test <- data.frame(
+ lapply(cats, function(x) { 
+  structure(x, class = c("avector", class(x))) 
+ }) 
+) 

> test 
    A.17272..1.MPR.rtn_rslt B.17272..1.MPR.rtn_rslt C.17272..1.MPR.rtn_rslt 
1      F      2.0      7.0 
2      F      2.0      7.4 
3      F      2.0      9.5 
4      F      2.1      7.2 
5      F      2.1      7.3 
6      F      2.1      7.6 
7      F      2.1      8.1 
8      F      2.1      8.2 
9      F      2.1      8.3 
10      F      2.1      8.5 

以上轉變導致新的數據testcats的到來,改變所有的特殊字符,例如:,.

回答

2

嘗試:

test <- data.frame(lapply(cats, function(x) { 
     structure(x, class = c("avector", class(x))) 
}), check.names = FALSE) 

你將不得不參考使用引號名稱或在某些情況下與格式背蜱,但它可能是最好重新命名整個數據幀。