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

From: hadley wickham <h.wickham_at_gmail.com>
Date: Thu, 27 Nov 2008 10:53:28 -0600

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/

______________________________________________
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 - 16:56:04 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 - 17:30:28 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