0

the following strange behavior is appearing in my code in R. This is my factor object:

R> pointsraw
[1] 2                 7                 6                 10                2/1-1/0.5        
[6] 1                 0.500000000000000 3                 1                 8                
[11] 7/1-5/0.7-3/0.4   3                 3/2-2/1           11/5-9/3-5/1      4                
[16] 4                 4/2/0             80                4/0               20               
[21] 2                 4/1-3/0.5        
18 Levels: 0.500000000000000 1 10 11/5-9/3-5/1 2 2/1-1/0.5 20 3 3/2-2/1 4 4/0 4/1-3/0.5 4/2/0 6 ... 80

This the first entry

R> pointsraw[[1]]
[1] 2
18 Levels: 0.500000000000000 1 10 11/5-9/3-5/1 2 2/1-1/0.5 20 3 3/2-2/1 4 4/0 4/1-3/0.5 4/2/0 6 ... 80

So far so good, but here comes the surprise:

R> as.numeric(pointsraw[[1]])
[1] 5

Question, why is this happening? How come 2 becomes 5?

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
OriolAnd
  • 13
  • 1
  • 7

1 Answers1

0

In R the factors are not necessarily mapped to their respective numbers because factors are just labels (they could be characters). Here is an example:

obs = as.factor(sample(sample(1:100,3),20,replace=T))
as.numeric(obs)

Gives:

> obs
 [1] 72 72 72 77 77 72 12 77 12 72 12 72 12 12 72 77 12 77 77 77
Levels: 12 72 77
> as.numeric(obs)
 [1] 2 2 2 3 3 2 1 3 1 2 1 2 1 1 2 3 1 3 3 3

Here are some functions to let you play with factors:

# dropping and setting levels
Z = as.factor(sample(LETTERS[1:5],20,replace=T))
levels(Z)
Y = as.factor(Z[-which(Z %in% LETTERS[4:5])])
levels(Y)
Y=droplevels(Y) # drop the levels
levels(Y)
levels(Y) = levels(Z) # bring them back
levels(Y)
Y = factor(Y,levels=LETTERS[1:7]) # expand them
levels(Y)
attr(Y,"levels")
attr(Y,"levels") = LETTERS[1:8] # keep expanding them
levels(Y)
require(plyr)
Y = mapvalues(Y,levels(Y),letters[1:length(levels(Y))]) # change the labels of the levels
levels(Y)
x<-factor(Y, labels=LETTERS[(length(unique(Y))+1):(2*length(unique(Y)))]) # change the labels of the levels on another variable
crogg01
  • 2,446
  • 15
  • 35