Как перекодировать переменную в числовой? - PullRequest
4 голосов
/ 15 июля 2011
> 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) заключалось в том, что если все результаты являются цифрами, они будут приведены к числовому.перекодировать в числовое значение?

Ответы [ 3 ]

5 голосов
/ 15 июля 2011

Если вы внимательно посмотрите документацию по 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)

edit Поскольку значение as.numeric.result по умолчанию равно TRUE, вам нужно только указать as.factor.result=FALSE, а не указывать оба из них.

3 голосов
/ 15 июля 2011

С ?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
3 голосов
/ 15 июля 2011

Попробуйте использовать as.numeric снова

> bar <- as.numeric(foo)
> bar
[1] 1 2 3 1
> str(bar)
 num [1:4] 1 2 3 1
...