Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change matrix column type in R

Tags:

r

matrix

I have a matrix and I want to change the fifth column type from character into numeric but I can not. I have tried this:

test1[,5] <- as.numeric(test1[,5])

but again the column class is character not numeric. What should I do? Thank you

like image 611
hora Avatar asked Dec 13 '12 11:12

hora


People also ask

How do I change the column names in a matrix in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I convert a matrix to a numeric matrix in R?

numeric() function with the name of the given character matrix as its parameter and this will help the user to convert the character matrix to numeric vector and in the next step user has to call another function matrix() with the numeric vector (which was created by the as.

How do I select a column in a matrix in R?

When we create a matrix in R, its column names are not defined but we can name them or might import a matrix that might have column names. If the column names are not defined then we simply use column numbers to extract the columns but if we have column names then we can select the column by name as well as its name.

How do you change a Dataframe to a matrix in R?

Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.


1 Answers

Like @Marius said, a matrix can only hold one data type. You could convert your matrix into a data.frame since data.frames can hold a different data type for each of their columns. The functions for converting from and back are as.data.frame and as.matrix. You'll then be able to apply the column conversion code you posted to a data.frame.

However, you mentioned in a comment that your ultimate goal was to reorder your matrix based on the values of a coerced column. You don't need to coerce the column in-place before reordering your matrix, you can do all that on the fly with:

test1[order(as.numeric(test1[, 5])), ]
like image 142
flodel Avatar answered Oct 16 '22 21:10

flodel