Search code examples
rtype-conversioncharacternumeric

Conversion in R from character to numeric generates NAs


I need to convert a column that is in "character" format into into a "numeric" format. However, when I perform the conversion, all the observations in that column become NAs. Any idea how to solve this? This is the code I am using:

bd$x2 <- as.numeric(as.character(bd$x))

The data comes from excel (that's why I am not able to share it with you). Anyone has faced a similar situation? How do you think I could solve this?


Solution

  • If your data s already a character you can simply delete that in your code , means

    bd$x2 <- as.numeric(bd$x)
    

    if your data already contains NA´s which are still saved as character make sure you save them as NA. For example like this:

    bd$x<- ifelse(bd$x=="NA", NA, bd$x)
    

    make sure, while loading the excel data into R, that you set the NA manually to NA. That should already solve the problem