Search code examples
rcoercion

Problems coercing factors into intergers


I am trying to convert a factor (tickets_other) in a data frame (p2) into an integer. Following the R help guide, as well as other advice from others, this code should work:

as.numeric(levels(p2$tickets_other))[p2$tickets_other]

The column does contain NAs, and so I get a warning:

Warning message:
NAs introduced by coercion

Which is fine, but after coercing it to numeric, it still reads as a factor:

class(p2$tickets_other)
[1] "factor"

The same result happens if I use as.numeric(as.character.()):

as.numeric(as.character(p2$tickets_other))
Warning message: 
NAs introduced by coercion 
class(p2$tickets_other)
[1] "factor"

Solution

  • I fixed the problem. It was actually very simple. The command:

    as.numeric(levels(p2$tickets_other))[p2$tickets_other]
    

    is correct, but I failed to store the result:

    p2$tickets_other <- as.numeric(levels(p2$tickets_other))[p2$tickets_other]
    

    Simple mistake, it retrospect. Thanks to DMT for the suggestion.