Factor with comma and percentage to numeric

元气小坏坏 提交于 2019-12-02 07:41:52

Another option is to use the parse_number-function from the readr-package and specify that a comma is used as decimal mark:

library(readr)
parse_number(rates, locale = locale(decimal_mark = ','))

which gives:

[1] -0.186 -0.229 -0.326

Used data:

rates <- as.factor(c("-0,186%", "-0,229%", "-0,326%"))

Use gsub:

# Example vector
vec <- as.factor(c("-0,186%", "-0,229%", "-0,326%"))

# Convert vector to numeric
vec <- as.numeric(gsub(",", ".", gsub("%", "", as.character(vec))))

I assume the levels of your initial factor are chars. Then you need to do both replacements at the same time:

rates=as.numeric(gsub(",", ".", gsub("%", "e-2", rates)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!