Character column with floats does not convert to numeric

Character column with floats does not convert to numeric



I have two variables of which the str() is listed below. I have tried everything to convert these columns to numeric, but they will not budge.


str()


$ ASKPRICE_B_B : atomic 4,47 4,49 4,47 4,36 ...
..- attr(*, "label")= chr "ASK PRICE_B_B"
..- attr(*, "format.stata")= chr "%9s"
$ BIDPRICE_B_B : atomic 4,4 4,39 4,33 4,29 ...
..- attr(*, "label")= chr "BID PRICE_B_B"
..- attr(*, "format.stata")= chr "%9s"



I have tried:


df$ASKPRICE_B_B <- as.numeric(as.character(df$ASKPRICE_B_B))



tried:


df$ASKPRICE_B_B <- as.numeric(gsub(",", ".", gsub("\.", "", df$ASKPRICE_B_B)))



tried:


df$ASKPRICE_B_B <- sub(",", ".", df$ASKPRICE_B_B)



Mostly giving the error:



Error: unexpected numeric constant in "X1809$ASKPRICE_B_B"


Error: unexpected numeric constant in "X1809$ASKPRICE_B_B"



I tried many other things but I cannot figure out what is going wrong..



I think it has something to do with the float being separated with a comma instead of a dot. Somehow I have not even been able to replace the comma with a dot.






How are you importing the data? Have you tried fixing the problem at import, with something like a dec = "," argument to read.table or read.csv?

– Gregor
Sep 18 '18 at 16:18


dec = ","


read.table


read.csv




2 Answers
2



Try:
as.numeric((gsub(",", ".", df$ASKPRICE_B_B)))


as.numeric((gsub(",", ".", df$ASKPRICE_B_B)))



PS: As suggested by @Gregor, you could set the right character used in the file for decimal points (here, dec = ",") while importing your data.


dec = ","






gsub returns a character always, so your as.character won't do anything.

– Gregor
Sep 18 '18 at 16:19


gsub


as.character






You're right, I wrote my answer too quickly. Thanks

– ANG
Sep 18 '18 at 16:22






Worked like a charm! Thank you so much!

– Tom
Sep 18 '18 at 16:26



. is a regex character. You need to escape them using or fixed = TRUE. Try.


df$ASKPRICE_B_B <- as.numeric(gsub(",", ".", as.character(df$ASKPRICE_B_B), fixed = TRUE))



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)