[R] as.numeric in data.frame, but only where it is possible

From: Kinoko <andzsinszan_at_gmail.com>
Date: Wed, 26 Nov 2008 22:53:09 -0800 (PST)


Hi,

I would like to convert my "character" sequences in my matrix/ data.frame into "numeric" where it is possible. I would also like to retain my alphabetic character strings in their original forms.

"5.1"     >   5.1
"hm"     >  "hm"

k<-matrix(c("aa", "bb", 1,2, 4.3, 0), nrow=2) mode(k) <- "numeric"
# ln1 coerces numeric chars into "character" and
# ln2 replaces alphabet chars with NA (with warnings)
# => OK as matrix can't have mixed types

k<-matrix(c("aa", "bb", 1,2, 4.3, 0), nrow=2) g<-as.data.frame(k, stringsAsFactos=FALSE) g[,2]
# returns:
# [1] 1 2
# Levels: 1 2
# hm... let them be levels then...

sum(g[,2])
# going down in flames

g[,2] <- as.numeric(g[,2])
sum(g[,2])
# is the winner of the day,
# but I have a hunch that there must be something more trivial/general
solution.

d<-data.frame("b"=seq(1,3))
d<-cbind(a,b)
typeof(d)
# "d" was coerced into "character"

any help is greatly appreciated,

gabor



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 27 Nov 2008 - 06:56:41 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 27 Nov 2008 - 18:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive