0

How to convert a column of class factor into numeric without disturbing the NAs present in it? I do not want to convert it to 0!!

   >Conceded
  [1] 665  515  NA   NA   NA   67   98   15   31   NA   NA   NA   NA   NA   2195 2525 1756 6366 3143
  [20] 7857 5926 2254 3199 4297 4568 2246 1506 2291
  21 Levels: 15 1506 1756 2195 2246 2254 2291 2525 31 3143 3199 4297 4568 515 5926 6366 665 67 ... 
  NA

   >class(Conceded)
         [1]"factor"

   >as.numeric(Conceded)
 [1] 17 14 21 21 21 18 20  1  9 21 21 21 21 21  4  8  3 16 10 19 15  6 11 12 13  5  2  7

1)How can I retain the value of NA,while converting a factor vector into a number vector? 2)Also what are these values that appear as a result oh this conversion 3) why do I need to convert to character vector followed by numeric vector?

B_man
  • 109
  • 1
  • 8

1 Answers1

2

You will probably need to first convert to a character, and then to numeric. Otherwise your factor levels are used for the values instead of the original values coded by the text.

Ex.

x <- factor(c(23,4,7,16, 10, NA))

as.numeric(x) # wrong values
as.numeric(as.character(x)) # correct values
Community
  • 1
  • 1
Marc in the box
  • 11,769
  • 4
  • 47
  • 97