【发布时间】: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 <- as.factor((1:10)/10) -
@CarlWitthoft:感谢您的澄清。
标签: r