[R] decimal separator from comma to dot

maxbre mbressan at arpa.veneto.it
Fri Aug 9 12:19:15 CEST 2013


This is my reproducible example

df<-structure(list(IDANT = c(37837L, 37838L, 37839L, 37840L, 37841L, 
37842L, 37843L, 40720L, 40721L, 40722L), N_TX = c(6L, 6L, 6L, 
4L, 1L, 1L, 1L, 2L, 2L, 1L), TILT = c(0L, 0L, 0L, 0L, 6L, 6L, 
6L, 0L, 0L, 0L), DIREZIONE = c(50L, 220L, 110L, 50L, 220L, 110L, 
50L, 170L, 70L, 270L), DATA_INI = structure(c(2L, 2L, 2L, 2L, 
2L, 2L, 2L, 1L, 1L, 1L), .Label = c("20/10/2004", "29/08/2002"
), class = "factor"), POT_TX = structure(c(4L, 4L, 4L, 3L, 2L, 
2L, 2L, 1L, 1L, 1L), .Label = c("10", "11,5", "4", "8"), class = "factor")),
.Names = c("IDANT", 
"N_TX", "TILT", "DIREZIONE", "DATA_INI", "POT_TX"), row.names = c(NA, 
10L), class = "data.frame")

The data frame “df” it’s a “simplified snapshot” from an oracle table
imported via odbc (by using the package RODBC) ;
now, the problem with the data frame “df” is that one variable “POT_TX” have
the decimal separator formatted with comma instead of dot; 
so I’m in the need to reformat the variable from factor to numeric type to
perform some useful calculations

this is my code I worked so far

#function to change comma to dot
myfun <- function(x) {sub(",",".",x)}

#apply the function to all variables
new <- apply(df, 2, myfun )
newdf <- data.frame(apply(new, 2, as.numeric))
str(newdf)

#apply the function to one variables
var<-as.numeric(sapply(df[,6], FUN=myfun))
df$POT_TX<-var
str(df)


my questions:

1.	is it possible to use the more convenient function “apply” with reference
to just some variables and not all of them? I’ve been reading on the help
that “Where X has named dimnames, it can be a character vector selecting
dimension names.”, what does exactly means that?

2.	do you know some more convenient methods to perform comma to dot
substitution in just some selected variables of a data frame? To note that
the desired final result is again a dataframe

3.	do you know any workaround to set the decimal delimiter for a variable
(field) “at the early steps” when connecting via odbc and then querying to
the table?
For these “early steps” I’ve been using something like:
library(RODBC)
con<-odbcConnect("dsn", uid="user", pwd="password")
df<-sqlQuery(con, "select * from table.name;")

thank you all for the eventual support




--
View this message in context: http://r.789695.n4.nabble.com/decimal-separator-from-comma-to-dot-tp4673414.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list