Cant convert factor to numeric in R

后端 未结 2 441
夕颜
夕颜 2021-01-16 17:00

I\'ve tried:

  • i <- as.numeric(as.character(Impress))

  • i <- as.numeric(as.character(levels(Impress)))

相关标签:
2条回答
  • 2021-01-16 17:04

    As far as the computer is concerned, , is not a number and hence any number string containing it must not be numeric, even if to a human these look like perfectly acceptable numbers.

    Get rid of the , and then it will work, e.g. using gsub()

    i <- as.numeric(gsub(",", "", as.character(Impress)))
    

    E.g.

    Impress <- c("24,085,563.00", "35,962,587.00", "31,714,513.00", "28,206,422.00")
    gsub(",", "", as.character(Impress))
    i <- as.numeric(gsub(",", "", as.character(Impress)))
    i
    
    R> gsub(",", "", as.character(Impress))
    [1] "24085563.00" "35962587.00" "31714513.00" "28206422.00"
    R> i
    [1] 24085563 35962587 31714513 28206422
    R> is.numeric(i)
    [1] TRUE
    
    0 讨论(0)
  • 2021-01-16 17:16

    Because the data has commas, R cannot convert it to a numeric. You have to remove the commas with sub() first and then convert:

    i <- as.numeric(gsub(",", "", as.character(impress)))
    
    0 讨论(0)
提交回复
热议问题