R 为什么可以';从其基础数据容器中生成因子?

R 为什么可以';从其基础数据容器中生成因子?,r,R,我试图理解R中数据容器的内部表示。因此,我尝试了以下方法: temp <- c(1,2,1,3,2) attr(temp,'levels') <- c('risky','safe','unsafe') attr(temp,'class') <- 'factor' temp 矩阵作为属性为“dim”的向量: 相当于 temp <- 1:6 attr(temp,'dim') <- c(3,2) temp list( integerCol=1:9, c

我试图理解
R
中数据容器的内部表示。因此,我尝试了以下方法:

temp <- c(1,2,1,3,2)
attr(temp,'levels') <- c('risky','safe','unsafe')
attr(temp,'class') <- 'factor'
temp
矩阵作为属性为“dim”的向量:

相当于

temp <- 1:6
attr(temp,'dim') <- c(3,2)
temp
list(
    integerCol=1:9,
    characterCol=sample(c('safe','risky','unsafe'),9,replace=TRUE),
    logicalCol=sample(c(T,F),9,replace=TRUE)
) -> temp
attr(temp,'class') <- 'data.frame'
attr(temp,'row.names') <- 1:9
temp
相当于

temp <- 1:6
attr(temp,'dim') <- c(3,2)
temp
list(
    integerCol=1:9,
    characterCol=sample(c('safe','risky','unsafe'),9,replace=TRUE),
    logicalCol=sample(c(T,F),9,replace=TRUE)
) -> temp
attr(temp,'class') <- 'data.frame'
attr(temp,'row.names') <- 1:9
temp
应等同于以下内容:

temp <- c(1,2,1,3,2)
attr(temp,'levels') <- c('risky','safe','unsafe')
attr(temp,'class') <- 'factor'
temp

temp在
因子
中,它将是
标签

factor(temp, labels = c('risky','safe','unsafe'))
#[1] risky  safe   risky  unsafe safe  
#Levels: risky safe unsafe
或者使用
结构

structure(temp, .Label = c('risky','safe','unsafe'), class = "factor")
谢谢你
结构(temp,levels=c('risk','safe','safe'),class='factor')
也可以工作。奇怪的是,使用
attr
为factor分配属性不起作用。从现在开始,我将只使用
结构
来分配属性。