Loop to convert decimal comma (,) into dot (.) to change class of data.frame columns

Viewed 5134

I would like to convert the decimal comma , into a dot .. As i'm not using read.table to import the data, i can't change it from the source. I'm actually using a query with RODBC package to import. And the database (Teradata) just outputs this way decimals. For this case in particular, i'm somehow forced to modify the data using regex. The point of this, is obviously to convert the object to numeric.

Here is an example

df <- data.frame(x1 = c("0,1012312", "0,165749", "0,12412", "0,6248223"), 
                 x2 = c("0,012312","0,5749", "0,112", "0,223"),
                 x1 = c("0,312", "0,65749", "0,2", "0,8223"), 
                 x2 = c("0,2312","0,49", "0,54412", "0,623")
                 , stringsAsFactors = FALSE)

df
str(df)

### What i've tried

attempt 1

for(i in 1:4){
  gsub(",", ".", df[ , i])
}

df

attempt 2

inx = 1:4
fc <- function(x, inx){
  nm <- names(x)[inx]
  gsub(pattern = ",", replacement = ".", x = x[nm])
}
sapply(df, fc, c(df, inx))

Neither works, however if i change each column individually it works.

i <- 1
gsub(",", ".", df[ , i])}
[1] "0.1012312" "0.165749"  "0.12412"   "0.6248223"
3 Answers
Related