4
> library(car)

> df = data.frame(value=c('A', 'B', 'C', 'A'))
> foo = recode(df$value, "'A'=1; 'B'=2; 'C'=3;", as.numeric.result=TRUE)
> mean(foo)
[1] NA
Warning message:
In mean.default(foo) : argument is not numeric or logical: returning NA
> foo
[1] 1 2 3 1
Levels: 1 2 3

啊。我认为as.numeric.result(默认为TRUE)的定义是,如果结果都是数字,它们将被强制转换为数字。

如何使重新编码的结果为数字?

4

3 回答 3

5

如果您仔细查看文档,recode您会看到:

as.factor.result     return a factor; default is TRUE if var is a factor, FALSE otherwise.
as.numeric.result    if TRUE (the default), and as.factor.result is FALSE, 
                      then the result will be coerced to numeric if all values in the 
                      result are numerals—i.e., represent numbers.

所以你需要指定as.factor.result=FALSE我认为:

foo = recode(df$value, "'A'=1; 'B'=2; 'C'=3;", as.factor.result=FALSE)

编辑 由于 的默认as.numeric.result值为 TRUE,因此您只需指定as.factor.result=FALSE,而不是同时指定它们。

于 2011-07-14T22:47:47.533 回答
3

as.numeric再次尝试使用

> bar <- as.numeric(foo)
> bar
[1] 1 2 3 1
> str(bar)
 num [1:4] 1 2 3 1
于 2011-07-14T22:43:05.163 回答
3

?recode您应该注意有关该论点的内容as.numeric.result

as.factor.result: return a factor; default is ‘TRUE’ if ‘var’ is a
          factor, ‘FALSE’ otherwise.

as.numeric.result: if ‘TRUE’ (the default), and ‘as.factor.result’ is
          ‘FALSE’, then the result will be coerced to numeric if all
          values in the result are numerals-i.e., represent numbers.

as.factor.result默认为,TRUE因此无论您设置什么,结果都将始终是一个因素as.numeric.result。要获得所需的行为,请同时设置as.factor.result = FALSE as.numeric.result = TRUE

> recode(df$value, "'A'=1; 'B'=2; 'C'=3;", as.numeric.result=TRUE, 
         as.factor.result = FALSE)
[1] 1 2 3 1
于 2011-07-14T22:57:06.557 回答