[英]Why R Changes Special Characters In Column Name To Dots
我有一個較大的數據集,當我導入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
上面的轉換導致來自cats
新數據test
,將所有特殊字符(例如:
和,
更改為.
。
嘗試:
test <- data.frame(lapply(cats, function(x) {
structure(x, class = c("avector", class(x)))
}), check.names = FALSE)
您將不得不使用引號或某些情況下的反引號引用格式的名稱,但重命名整個數據框可能更可取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.