如何将变量重新编码为数字?

dfr*_*kow 4 r r-car

> 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
Run Code Online (Sandbox Code Playgroud)

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

如何将此重新编码的结果设为数字?

jor*_*ran 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.
Run Code Online (Sandbox Code Playgroud)

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

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

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