I'm trying to understand how various objects in R are composed of atomic and generic vectors.
One can construct a data.frame
out of a list
by manually setting the attributes names
, row.names
, and class
, see here.
I wonder how this might work for factors, which are internally represented as integer vectors. The solution I came up with is the following:
> f <- 1:3
> class(f) <- "factor"
> levels(f) <- c("low", "medium", "high")
Warning message:
In str.default(val) : 'object' does not have valid levels()
But for some reason this still looks different than a properly constructed factor:
> 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"
Am I missing something? (I know this probably should not be used in production code, instead it is for educational purposes only.)