简体   繁体   English

R 中数值的因素

[英]Factors to Numeric in R

I was following along to this post here to figure out how to change my factor into a numeric value in R Studio.我一直在关注这篇文章以了解如何在 R Studio 中将我的因子更改为数值。 The factor in question does have NA's which I put in there myself.有问题的因素确实有我自己放在那里的NA。 I need to use this factor in a tapply() code later and want to make sure that the NA's won't be a problem.稍后我需要在tapply()代码中使用这个因素,并希望确保 NA 不会成为问题。

Example Code:示例代码:

factor.1[2] <-NA
factor.1[7] <-NA
factor.1[12] <-NA

Then, following the directions on the linked post:然后,按照链接帖子上的说明:

num.fact1 <- as.numeric(levels(factor.1))[factor.1]

The "error" I get is "NA's introduced by coercion".我得到的“错误”是“强制引入的 NA”。 But it does let me proceed, regardless.但无论如何,它确实让我继续。 Now, tapply:现在,点击:

tapply(
    num.fact1,
    factor.2,
    mean, na.rm=TRUE
)

I think the output looks fine/accurate.我认为 output 看起来不错/准确。 I want to make sure that the error I have with "NA's introduced by coercion" won't be a problem, especially when I knit this notebook to PDF.我想确保我遇到的“强制引入的 NA”错误不会成为问题,尤其是当我将此笔记本编织到 PDF 时。

Assigning the NA to the variable is harmless in this case.在这种情况下,将 NA 分配给变量是无害的。 The cause of the warning, however, is more worrying.然而,警告的原因更令人担忧。 Look at this example:看这个例子:

factor.1 <- factor(c("5.6", "4.7", "10.1", "2.O", "3.6", "1.7"))
factor.1
# [1] 5.6  4.7  10.1 2.O  3.6  1.7 
# Levels: 1.7 10.1 2.O 3.6 4.7 5.6

They all look like numbers, right?它们看起来都像数字,对吧? Now do your conversion to numeric:现在转换为数字:

num.fact.1 <- as.numeric(levels(factor.1))[factor.1]
# Warning message:
# NAs introduced by coercion

The message is warning you that some of the data could not be converted to numeric, so NA results.该消息警告您某些数据无法转换为数字,因此结果为 NA。 Let's check which ones:让我们检查一下:

data.frame(factor.1, num.fact.1)[which(is.na(num.fact.1) & !is.na(factor.1)), ]
#   factor.1 num.fact.1
# 5      2.O         NA

The 5th data is "2.O" not 2.0.第 5 个数据是“2.O”而不是 2.0。 The data may need some cleaning.数据可能需要一些清理。

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

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