Is there a proper function for transforming a character to a number instead of using i=match('c',letters) # 3 Thanks. Josef Eschgf??ller -- Josef Eschgf??ller Dipartimento Matematico Universita' di Ferrara http://felix.unife.it
Josef, Not sure if this is exactly what you mean, but there is a generic function as() to which you can then specify "numeric" as an argument and which then coerces stuff into numeric format. Tobias Josef Eschgfaeller wrote:> > Is there a proper function for transforming > a character to a number instead of using > > i=match('c',letters) > # 3 > > Thanks. > Josef Eschgf??ller > > > ------------------------------------------------------------------------ > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html-- ************************************************************************** When Thomas Edison invented the light bulb he tried over 2000 experiments before he got it to work. A young reporter asked him how it felt to have failed so many times. He said "I never failed once. I invented the light bulb. It just happened to be a 2000-step process."
Josef Eschgfaeller wrote:> > Is there a proper function for transforming > a character to a number instead of using > > i=match('c',letters) > # 3I'd suggest to use the above if you really mean it. Note that "transforming a character to a number" is not well defined, because you have to think about encodings and characters at first. See the article by Brian Ripley in the most recent issue of R News, for example. Uwe Ligges> Thanks. > Josef Eschgf??ller > > > ------------------------------------------------------------------------ > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> as.numericSome weeks ago one discussed on the list about how to transform a hexadecimal representation to decimal digits. Specifically one has to transform 'a' to 10 etc. In C one does this with 'a'-87, but I did not find a function for this in R. Using match on letterdigits as in the following is of course a little slow when repeated often. --------------------------------------- Hex = function (rep16) {rep16=tolower(rep16) u=strsplit(rep16,'',perl=T)[[1]] letterdigits=c(0:9,letters) v=sapply(u,function (x) match(x,letterdigits)-1) v=as.numeric(v) Horner(v,16)} Horner = function (v,alfa=2) {b=v[1]; m=length(v) if (m>1) for (i in 2:m) b=b*alfa+v[i]; b} # Example: for (x in c('0','a0','10e','f0ae')) print(Hex(x)) # 0 # 160 # 270 # 61614 --------------------------------------- Josef Eschgf??ller -- Josef Eschgf??ller Dipartimento Matematico Universita' di Ferrara http://felix.unife.it