[R] as.numeric in data.frame, but only where it is possible
hadley wickham
h.wickham at gmail.com
Thu Nov 27 17:53:28 CET 2008
On Thu, Nov 27, 2008 at 12:53 AM, Kinoko <andzsinszan at gmail.com> wrote:
> 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)
Try this:
g <-as.data.frame(k, stringsAsFactors = FALSE)
str(g)
g[] <- lapply(g, type.convert)
str(g)
Hadley
--
http://had.co.nz/
More information about the R-help
mailing list