我試圖了解 R 中的各種物件是如何由原子向量和通用向量組成的。
可以通過手動設定屬性、、 和來構造一個data.frameout ,請參見此處。listnamesrow.namesclass
我想知道這如何適用于在內部表示為整數向量的因子。我想出的解決方案如下:
> f <- 1:3
> class(f) <- "factor"
> levels(f) <- c("low", "medium", "high")
Warning message:
In str.default(val) : 'object' does not have valid levels()
但出于某種原因,這看起來仍然與正確構造的因素不同:
> str(unclass(f))
int [1:3] 1 2 3
- attr(*, "levels")= chr [1:3] "low" "medium" "high"
> str(unclass(factor(c("low", "medium", "high"))))
int [1:3] 2 3 1
- attr(*, "levels")= chr [1:3] "high" "low" "medium"
我錯過了什么嗎?(我知道這可能不應該用于生產代碼,而是僅用于教育目的。)
uj5u.com熱心網友回復:
順序很重要。
f <- 1:3
levels(f) <- c("low", "medium", "high") ## mark
class(f) <- "factor"
f
# [ 1] low medium high
# Levels: low medium high
`levels<-`向向量添加一個屬性,而不是行## 標記,您也可以這樣做
attr(f, 'levels') <- c("low", "medium", "high")
這里一步一步發生了什么:
f <- 1:3
attributes(f)
# NULL
levels(f) <- c("low", "medium", "high")
attributes(f)
# $levels
# [1] "low" "medium" "high"
class(f) <- "factor"
attributes(f)
# $levels
# [1] "low" "medium" "high"
#
# $class
# [1] "factor"
檢查“自動”因子生成。
attributes(factor(1:3, labels=c("low", "medium", "high")))
# $levels
# [1] "low" "medium" "high"
#
# $class
# [1] "factor"
而且,重要的是
stopifnot(all.equal(unclass(f),
unclass(factor(1:3, labels=c("low", "medium", "high")))))
注1,順序f無關緊要。的級別f由它們的索引標識,分配的級別向量的元素n成為第一級,即`1`='low', `2`='medium', `3`='high'在以下示例中。
f <- 3:1
levels(f) <- c("low", "medium", "high")
class(f) <- 'factor'
f
# [1] high medium low
# Levels: low medium high
注意 2,這僅在f以 開頭1并且級別增加時才有效1,因為因子實際上是標記的整數結構。
g <- 2:4
levels(g) <- c("low", "medium", "high")
class(g) <- 'factor'
g
# Error in as.character.factor(x) : malformed factor
h <- c(1, 3, 4)
levels(h) <- c("low", "medium", "high")
class(h) <- 'factor'
# Error in class(h) <- "factor" :
# adding class "factor" to an invalid object
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393440.html
上一篇:如何洗掉具有特定字串的所有行?
下一篇:選擇組中倒數第二小的日期
