简体   繁体   English

在R中使用as.numeric()转换时出错

[英]Error when converting with as.numeric() in R

I have a dataset: 我有一个数据集:

 > x
    Treatment X1 X2
1         T1  6  7
2         T1  5  9
3         T1  8  6
4         T1  4  9
5         T1  7  9
6         T2  3  3
7         T2  1  6
8         T2  2  3
9         T3  2  3
10        T3  5  1
11        T3  3  1
12        T3  2  3

I am trying to find means of the columns X1 and X2. 我正在尝试查找X1和X2列的方法。 If I run the data as-is, I get an error: 如果按原样运行数据,则会出现错误:

> t1 <- subset(x[2:3], x$Treatment=="T1")
> x_vec <- colMeans(t1, na.rm = TRUE)
Error in colMeans(t1, na.rm = TRUE) : 'x' must be numeric

So, I need to convert X1 and X2 to numeric: 因此,我需要将X1和X2转换为数字:

t1$X1 <- as.numeric(as.factor(t1$X1))
t1$X2 <- as.numeric(as.factor(t1$X2))
x_vec <- colMeans(t1, na.rm = TRUE)

But when I do that, I get the wrong result: 但是当我这样做时,我得到了错误的结果:

> x_vec
 X1  X2 
6.0 4.4 

The t1, after conversion to as.numeric() , shows: 转换为as.numeric()之后,t1显示:

> t1
  X1 X2
1  6  4
2  5  5
3  8  3
4  4  5
5  7  5

Why are the values in X2 changed after converting to numeric? 转换为数字后,为什么X2中的值会更改?

This is a pretty common issue that newer R users hit. 这是新R用户遇到的一个非常普遍的问题。 The issue is your use of as.factor . 问题是您对as.factor的使用。 running as.numeric on a factor converts the value to the numeric index of the label, rather than converting the label itself to a number. 在一个因子上以as.numeric运行将值转换为标签数字索引 ,而不是将标签本身转换为数字。 Your can either remove the call to as.factor or run as.character on the factor before calling as.numeric . 你可以删除调用as.factor或运行as.character调用之前的因素as.numeric

Note that some functions like as.data.frame automatically convert characters to factors, which can cause problems. 请注意,诸如as.data.frame类的某些功能会自动将字符转换为因数,这可能会导致问题。 Check out the option stringsAsFactors for more info. 查看选项stringsAsFactors以获得更多信息。

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

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