0

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"
David Johnson
  • 439
  • 1
  • 3
  • 13

2 Answers2

0

You're doing:

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

You are reading the levels from p2$tickets_other (a vector), then converting them to numeric (still a vector), then accessing the indices of that vector according to the values in p2$tickets_other

I can't imagine this is what you really want to do.

Maybe just

as.numeric(p2$tickets_other)

is what you want?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
rcorty
  • 1,140
  • 1
  • 10
  • 28
0

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.

David Johnson
  • 439
  • 1
  • 3
  • 13