Skip to content
Prev 262550 / 398502 Next

How to create a numeric data.frame

Hi,

If your matrix is already numeric, then:

as.data.frame(your_matrix_name)

will do the trick.  However, if you have a matrix that is not numeric
(say it is character), then you could use:

as.data.frame(as.numeric(your_matrix_name))

Matrices can only hold one class of data (for example, all numeric, or
all character, or all factor), so if *any* of your data is character
(say one column contains people's names), then the entire matrix will
be character, and calling as.numeric() on it is probably not what you
want (the character data will get screwed up).  In which case, you
might convert the matrix to a data frame first:

as.data.frame(your_matrix_name)

because data frames can contain different classes of data in their
different columns.  Once it is a data frame, you could convert the
columns that should be numeric to numeric (say, columns 2 through 6
only) by:

your_data_name[, 2:6] <- lapply(your_data_name[, 2:6], as.numeric)

For relevant documentation, see

?as.numeric
?as.data.frame
## under the "Details" section, it shows the hierarchy of data types
## that is how I could know that if there is character data, the numeric
## data will be converted up to the character class
?matrix


Hope this helps,

Josh
On Mon, Jun 13, 2011 at 3:06 AM, Aparna <aparna.sampath26 at gmail.com> wrote: