【问题标题】:How to code categorial variables as numeric in R如何在R中将分类变量编码为数字
【发布时间】:2015-03-10 19:58:38
【问题描述】:

我正在分析库 HSAUR2 中的 R 中的 CHFLS 数据集。我想为这些数据拟合一个线性模型,以找出其他变量对变量 R_happy 的影响; R_happy 已被编码,因此 1 表示“非常高兴”,否则表示 0。我只是想知道如何将其余变量编码,例如,R_region 为数字,以便我可以使用虚拟变量并拟合线性模型?我试过使用 as.numeric 但它没有用。我的代码如下:

加载必要的库

library("HSAUR2") #Load necessary library
data(CHFLS,package="HSAUR2") #Load the Chinese Health and Family Life Survey data

View(CHFLS) #Read details about the data, including the covariates.
help("CHFLS")

summary(CHFLS) #Produce a summary of the data

#Pie chart showing womens self reported happiness
slices <- c(280, 1254)
lbls <- c("Very happy (18.25%)", "Otherwise(81.75%)")
pie(slices, labels=lbls)

#Define the variable of interest to be y which is 1 when
#"Very happy" (or greater) and 0 otherwise
y<-(CHFLS$R_happy>="Very happy")

# Append y onto the data and call the new data CHFLSnew
CHFLSnew<-cbind(CHFLS,y)

# Ensure that any categorical variables are coded as factors.
CHFLSnew$y<-as.factor(CHFLSnew$y)

##Append y as factor onto CHFLSnew
CHFLSnew<-cbind(CHFLS,y)

【问题讨论】:

  • 如果变量在概念上是分类的,则将其保留为因子。 R 将在幕后为您处理一切。
  • 省点麻烦:R_region 是什么类?当您尝试 as.numeric 时会发生什么?例如,如果是factor,则需要使用as.numeric(as.character( ))
  • @CarlWitthoft :即使没有“as.character”转换,as.numeric 也可以使用因子。输出是相同的。
  • @mso - 只有当因子“名称”碰巧与因子顺序中的索引值相同时才会如此。试试看,例如,foo &lt;- as.factor((1:10)/10)
  • @CarlWitthoft:感谢您的澄清。

标签: r


【解决方案1】:

一般来说,如果您想将factor 转换为numeric

f <- factor(1:10)
f
[1] 1  2  3  4  5  6  7  8  9  10
Levels: 1 2 3 4 5 6 7 8 9 10

n <- as.numeric(levels(f)[f])
n
[1]  1  2  3  4  5  6  7  8  9 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2020-07-01
    • 2019-03-28
    • 2011-05-26
    • 2018-06-03
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多