Replacing commas and dots in R

半世苍凉 提交于 2019-11-30 05:11:18

You need to escape the "." in your regular expression, and you need to replace the commas with a "." before you can convert to numeric.

> as.numeric(gsub(",", ".", gsub("\\.", "", var1)))
[1]   50   72  960 1920   50   50  960

For things like these I like scan() the most, because it is easy to understand. Just use

scan(text=var1, dec=",", sep=".")

Alas, it's not faster than gsub(), which on the other hand seemes overpowered. Hence another, and fast, option is sub():

as.numeric(sub(",", ".", sub(".", "", var1, fixed=TRUE), fixed=TRUE))

And just in case: When you're reading var1 from a file directly, just read it in with a specified separator: read.table("file.txt", dec=",", sep=".")

You can use function "type_convert", from "readr" package. I am reading an ODS file (Locale Portuguese), and converting the numbers:

library('readODS')
library('tidyverse')
data <- read_ods('mod-preditivo.ods', sheet=1,col_names = TRUE,range='a1:b30',col_types=NA)
df <- type_convert(data,trim_ws=TRUE,col_types = cols(Pesos=col_integer(),Alturas=col_double()),locale = locale(decimal_mark = ","))
str(df)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!