简体   繁体   English

如何在R中改变对定量的分类响应?

[英]How to change categorical responses to quatitative in R?

我有一个数据表,其中包含男性和女性的列,以及一个有和没有响应的数据表,我只需要将这些更改为0和1值,我该如何处理?

I doubt that you really do need to do this but here's how (assuming they are factors): 我怀疑你确实需要这样做,但这是如何(假设它们是因素):

numMF <- as.numeric(MFfac) -1 # will be 0 for F and 1 for M in the usual sorting of factor levels

If they are really character vectors, then wrap factor around the MFfac that I assumed was a factor. 如果它们确实是特征向量,那么我认为MFfac是一个因素。 Or: 要么:

numMF <- match(MFvec, c("Female", "Male") ) -1

 match( c("Female","Male", "Female"),  c("Female", "Male") )
[1] 1 2 1

The match function is an important resource for data conversions. 匹配函数是数据转换的重要资源。

You can coerce a factor directly to a numeric vector: as.numeric(factor(x)) . 您可以直接将因子强制转换为数字向量: as.numeric(factor(x)) If the default level ordering is not to your liking, specify the levels explicitly with the "levels" argument to "factor". 如果默认级别排序不符合您的喜好,请使用“factor”的“levels”参数明确指定级别。

The general way to convert factors to indicator variables is using the model.matrix function. 将因子转换为指标变量的一般方法是使用model.matrix函数。 But most of the time you don't need to do this because the modeling functions (such as lm ) will call model.matrix for you. 但大多数情况下你不需要这样做,因为建模功能(如lm )会为你调用model.matrix

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM