Re: [R] Converting characters to numbers in data frames

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Thu 25 Aug 2005 - 22:36:47 EST

On 8/25/05, Anon. <bob.ohara@helsinki.fi> wrote:
> I'm sure I'm missing something obvious here, but I can't find the
> solution (including in the FAQ etc.).
>
> I have a vector of names of variables like this: NRes.x.y. where x and y
> are numbers. I want to extract these numbers as numbers to use
> elsewhere. I can extract the numbers as a list of characters using
> strsplit(), and convert that to a data frame, e.g.:
>
> NAMES=c("NRes.1.2.", "NRes.1.3.", "NRes.1.4.", "NRes.1.5.", "NRes.1.6.")
> NUMBERS=strsplit(gsub("NRes.","", NAMES, perl =T), '.', fixed = TRUE)
> NUMBERS.df=t(data.frame(NUMBERS))
>
> But I now want to convert the characters to be numeric. Using
> as.numeric(NUMBERS.df) converts them, but to a vector. How can I
> convert and keep as a data frame? I could use this:
>
> matrix(as.numeric(NUMBERS.df), ncol=dim(NUMBERS.df)[2])
>
> but I seem to be jumping through far too many hoops: there must be an
> easier way. An suggestions?

Try this:

   read.table(textConnection(NAMES), sep = ".")[,2:3]

You may also want to add the col.names= argument to the read.table call if you want prettier column names. Also I think Names and Numbers would be sufficient to distinguish them from potential lower case counterparts.



R-help@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 Received on Thu Aug 25 22:41:43 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 15:51:02 EST