Skip to content

How to convert character matrix or data.frame to numeric?

4 messages · ivan popivanov, Gabor Grothendieck, Ben Tupper +1 more

#
Try this:

class(mm) <- "numeric"

On Sun, Jan 17, 2010 at 5:17 PM, ivan popivanov
<ivan.popivanov at hotmail.com> wrote:
#
Hi,

I find the following works in R 2.10.1 on Mac OSX.

 > m = matrix(rep("3", 30), 5,6)
 > m
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "3"  "3"  "3"  "3"  "3"  "3"
[2,] "3"  "3"  "3"  "3"  "3"  "3"
[3,] "3"  "3"  "3"  "3"  "3"  "3"
[4,] "3"  "3"  "3"  "3"  "3"  "3"
[5,] "3"  "3"  "3"  "3"  "3"  "3"
 > apply(m, 1,as.numeric)
      [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    3    3    3
[2,]    3    3    3    3    3
[3,]    3    3    3    3    3
[4,]    3    3    3    3    3
[5,]    3    3    3    3    3
[6,]    3    3    3    3    3

Cheers,
Ben
On Jan 17, 2010, at 5:17 PM, ivan popivanov wrote:

            
Cheers,
Ben
#
In respect of your matrix problem:

(1) mode(mm) <- "numeric"

OR:

(2) mm <- apply(mm,2,as.numeric)

In respect of your data frame problem:

	as.data.frame(lapply(X,as.numeric))

(where X is your data frame) should work.  This will of course
convert every column of your data frame to numeric mode.  If there
are some columns that you wish to leave alone you will have to do
something a little bit more subtle.  But not much more subtle.
It's all pretty easy if you learn some basic R syntax.

	cheers,

		Rolf Turner
On 18/01/2010, at 11:17 AM, ivan popivanov wrote:

            
######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}